【问题标题】:Ruby 'sub!' doesn't replace text if/elsif statements [duplicate]红宝石“潜艇!”不替换文本 if/elsif 语句 [重复]
【发布时间】:2013-03-24 19:36:56
【问题描述】:

这让我发疯的时间比它应该的要长得多,我正在使用简单的字符串替换,但它无法根据它获得的信息替换字符串(在这种情况下,它是'url')。

class Test
  myURL = 'www.google.com'
puts 'Where are you from?'
  location = gets
    if location == 'England'
     myURL['.com'] = '.co.uk'
    elsif location == 'France'
     myURL['.com'] = '.co.fr'
    end
puts myURL
end

我疯了吗?

【问题讨论】:

  • 您没有在代码中使用sub!

标签: ruby string replace gsub


【解决方案1】:

location = gets 更改为location = gets.chomp

gets 发生的情况是它正在拾取您在提示中键入的所有内容,其中包括 Enter 键。所以,如果你输入“英格兰”,那么:

location == "England\n" #=> true
location == "England"   #=> false

String#chomp 方法将删除末尾的终止行。

【讨论】:

    【解决方案2】:

    您只需要这样做:

    class Test
        myURL = 'www.google.com'
        puts 'Where are you from?'
        location = gets.chomp
        if location == 'England'
            myURL['.com'] = '.co.uk'
        elsif location == 'France'
            myURL['.com'] = '.co.fr'
        end
        puts myURL
    end
    

    原因是gets返回的字符串末尾有换行符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      相关资源
      最近更新 更多