2013-03-24 41 views
0

这使我疯狂了很久,我使用SIMPLE字符串替换,但它无法替换字符串(在这种情况下,它是'url' )根据它获得的信息。Ruby'sub!'如果/ elsif语句不会替换文本

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 

我会疯了吗?

+0

你不在代码中使用'sub!'。 – 2013-03-25 03:38:34

回答

8

变化location = getslocation = gets.chomp

什么用gets发生的是它拿起你键入到提示其中包括输入关键的一切。所以,如果你在“英格兰”,然后键入:

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

String#chomp方法将删除末尾的端接线路。

1

你只需要做到:

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返回的字符串有在最后一个换行符。