2015-03-03 53 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})"