Can';t访问在我的ruby函数外部定义的数组
如何访问函数外部定义的数组?我尝试添加Can';t访问在我的ruby函数外部定义的数组,ruby,Ruby,如何访问函数外部定义的数组?我尝试添加$coins.length,正如我在某个地方读到的全局变量一样,它不起作用。我之所以在外部定义数组,是因为下面还有其他函数将新项推送到同一数组中 coins = [] def start puts "It's a sunny day. It's warm and you feel great." puts "You've picked up your son from creche. He's in a good mood and you
$coins.length
,正如我在某个地方读到的全局变量一样,它不起作用。我之所以在外部定义数组,是因为下面还有其他函数将新项推送到同一数组中
coins = []
def start
puts "It's a sunny day. It's warm and you feel great."
puts "You've picked up your son from creche. He's in a good mood and you've got home no problem."
puts "This is when troubles start, and you know it."
puts "You go out of the elevator and before you reach the door... 'give me the keeys'!"
puts "Do you give him the keys? (Y/N)"
print "> "
while keys = gets.chomp.downcase
case keys
when "y"
puts "you are in, good job. And you get a coin"
coins.push("1")
puts "you now have #{coins.length} coins"
room
when "n"
cry("I wanted to dooooooo iiiiiiiit!")
else
again
end
end
end
不要定义全局变量,而是尝试定义一种可以在任何地方使用的方法,如:
def coins
@coins ||= []
end
def start
puts "It's a sunny day. It's warm and you feel great."
puts "You've picked up your son from creche. He's in a good mood and you've got home no problem."
puts "This is when troubles start, and you know it."
puts "You go out of the elevator and before you reach the door... 'give me the keeys'!"
puts "Do you give him the keys? (Y/N)"
print "> "
while keys = gets.chomp.downcase
case keys
when "y"
puts "you are in, good job. And you get a coin"
coins.push("1")
puts "you now have #{coins.length} coins"
room
when "n"
cry("I wanted to dooooooo iiiiiiiit!")
else
again
end
end
end
这样,该方法将不会是全局的,其他方法也可以访问文件中的该方法(
coins
)。不要定义全局变量,而是尝试定义一个可以在任何地方使用的方法,如:
def coins
@coins ||= []
end
def start
puts "It's a sunny day. It's warm and you feel great."
puts "You've picked up your son from creche. He's in a good mood and you've got home no problem."
puts "This is when troubles start, and you know it."
puts "You go out of the elevator and before you reach the door... 'give me the keeys'!"
puts "Do you give him the keys? (Y/N)"
print "> "
while keys = gets.chomp.downcase
case keys
when "y"
puts "you are in, good job. And you get a coin"
coins.push("1")
puts "you now have #{coins.length} coins"
room
when "n"
cry("I wanted to dooooooo iiiiiiiit!")
else
again
end
end
end
这样,该方法将不会是全局的,其他方法也可以在文件中访问该方法(
coins
)。Ruby是一种面向对象的语言。更重要的是,Ruby带着一句格言出现在现场“一切都是一个对象”。Ruby中的偶数和(sic!)nil
都是对象:
▶ 42.class
#⇒ Fixnum < Integer
▶ nil.__id__
#⇒ 8
Ruby是一种面向对象的语言。更重要的是,Ruby带着一句格言出现在现场“一切都是一个对象”。Ruby中的偶数和(sic!)
nil
都是对象:
▶ 42.class
#⇒ Fixnum < Integer
▶ nil.__id__
#⇒ 8
| |=的有趣用法。我读了很多书,比如,但我还是不知道它在这种情况下起什么作用。有趣的是@coins=[]不起作用。能详细说明一下| |=在这种情况下做了什么吗?谢谢
foo | |=42
是foo=foo | | 42
的缩写,例如,`foo+=42`是foo=foo+42
的缩写。这里它用于设置@coins
实例变量,前提是之前没有设置它。我读了很多书,比如,但我还是不知道它在这种情况下起什么作用。有趣的是@coins=[]不起作用。能详细说明一下| |=在这种情况下做了什么吗?谢谢foo | |=42
是foo=foo | | 42
的缩写,例如,`foo+=42`是foo=foo+42
的缩写。这里它用于设置@coins
实例变量,前提是之前没有设置它。这可能是我得到的最清晰的答案之一,grácies!也许是我得到的最清晰的答案之一,grácies!