2015-03-03 54 views
-1

這顯示了一個錯誤,因爲ruby範圍規則阻止我訪問if else塊內的外部變量。如何繞過紅寶石範圍約定如果else語句

puts "Enter Line 1 m and c:" 
m1 = gets.to_f 
c1 = gets.to_f 

puts "Enter Line 2 m and c:" 
m2 = gets.to_f 
c2 = gets.to_f 

if ((m1==m2) and (c1==c2)) 
    puts "infinite solutions" 
elsif ((m1==m2) and (c1!=c2)) 
    puts "no solution" 
else 
    x = (c1 - c2)/(m2 - m1) 
    y = m1*x + c1 
    puts "(x,y) = (" + x + "," + y+")" 
end 

你能告訴我一種方法來解決這個錯誤嗎?

更新:

實際上我得到的錯誤是: 未定義局部變量或者用於主要方法 'C1' :7 選自C;/Ruby200-X64 /斌/ IRB:從對象12;在''

+0

你的條件對'elsif'是多餘的。 'm1 == m2'就足夠了。 – sawa 2015-03-03 14:30:54

+0

你得到的範圍錯誤是什麼?我沒有看到範圍有什麼問題。問題不明確。 – sawa 2015-03-03 14:34:29

+0

我無法重現此錯誤。提到的一個錯誤是http://stackoverflow.com/a/28834277/2597260和http://stackoverflow.com/a/28834227/2597260在「puts」(x,y)=(「+ x +」, 「+ y +」)「'。我已經嘗試過在2.0.0(在家中)和網站上使用插值的代碼:http://repl.it/cbg(2.2.0),它工作。 – 2015-03-03 15:30:27

回答

2

使用interpolation擺脫這一點。

puts "(x,y) = (#{x}, #{y})" 

你試圖連擊StringFloat對象的對象。這是不可能的,所以你必須在級聯之前將那些Float轉換爲String對象。

修改後的代碼:

puts "Enter Line 1 m and c:" 
m1 = gets.to_f 
c1 = gets.to_f 

puts "Enter Line 2 m and c:" 
m2 = gets.to_f 
c2 = gets.to_f 

if m1 == m2 and c1 == c2 
    puts "infinite solutions" 
elsif m1 == m2 and c1 != c2 
    puts "no solution" 
else 
    x = (c1 - c2)/(m2 - m1) 
    y = m1*x + c1 
    puts "(x,y) = (#{x}, #{y})" 
end 

輸出

[[email protected]]$ ruby a.rb 
Enter Line 1 m and c: 
14 
21 
Enter Line 2 m and c: 
12 
44 
(x,y) = (11.5, 182.0) 
[[email protected]]$ 
+0

但我仍然得到相同的錯誤。這並沒有做任何事情來糾正範圍問題,是嗎?另外,你能解釋一下這段代碼嗎?什麼是插值? – 2015-03-03 14:28:04

+0

@RahulKejriwal沒有_scope_問題。有什麼_type conversion_問題。 – 2015-03-03 14:32:07

+0

實際上,我得到的錯誤是: 未定義的局部變量或方法'c1'for main:Object from :7 from C;/Ruby200-x64/bin/irb:12; in'

' – 2015-03-03 14:37:41

1

它不會阻止您訪問外部變量,你看到的錯誤是:

` +':沒有將Float轉換爲字符串(Ty peError)

這是完全不同的,與變量可見性範圍無關。說錯誤的是,您無法總結StringFloat(在控制檯中嘗試'a' + 1.0)。

要解決它,你應該自己轉換變量字符串用:

puts "(x,y) = (" + x.to_s + "," + y.to_s + ")" 

或使用interpolation(這是優選的):

puts "(x,y) = (#{x}, #{y})"