如何访问函数外部定义的数组?我已经尝试添加$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
答案 0 :(得分:2)
Ruby是一种面向对象的语言。更重要的是,Ruby出现在场景中,其座右铭是“一切都是对象。”Ruby中的偶数和(sic!)nil
是对象:
▶ 42.class
#⇒ Fixnum < Integer
▶ nil.__id__
#⇒ 8
所以,你应该把对象用于比单线程稍微复杂的任何东西。对象具有很多开箱即用的优点:实例变量,生命周期等。
class Game
def initialize
@coins = []
end
def add_coin(value)
@coins << value
end
def coins
@coins
end
def amount
@coins.size
end
end
现在你可以在这个类的实例中创建它并且当它处于活动状态时,它将保持@coins
的值:
game = Game.new
game.add_coin("1")
puts game.coins
#⇒ ["1"]
puts game.amount
#⇒ 1
game.add_coin("1")
game.add_coin("2")
puts game.coins
#⇒ ["1", "1", "2"]
puts game.amount
#⇒ 3
答案 1 :(得分:1)
而不是定义全局变量,尝试定义一个可以在任何地方使用的方法,例如:
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
)。