2013-03-24 24 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返回的字符串有在最後一個換行符。