我现在正在学习Ruby,使用http://www.humblelittlerubybook.com/book/html/chapter2.html的教程
我目前所处的子章节是:“方法和变量”
我已经创建了一个Boogeyman类的实例数组,我想调用这些实例的每个'change_location'方法,并将它们的实例变量@location更改为数组指定的值。
class Boogeyman
def initialize(name, location)
@name = name
@location = location
puts "Yes, Master?"
end
def change_location(newlocation)
@location = newlocation
puts "I moved to #{newlocation}."
self.get_info
end
def change_name(newname)
@name = newname
puts "I shall be called #{newname} from now on!"
self.get_info
end
def get_info
puts "I am #{@name} in #{@location}."
end
end
army = Array.new
army.push(Boogeyman.new("Mister Creepy", "New York, NY"))
army.push(Boogeyman.new("Loopy Lou", "Albuquerque, NM"))
locations = ["location1", "location2"]
换句话说:我想改变军队中所有boogeymen的位置 我已经学习了.each方法,并期望以下列方式为数组中的所有位置提供“位置”:
army.each {|boogeyman| boogeyman.change_location(locations)}
或:
army.each(locations) {|boogeyman| boogeyman.change_location(locations)}
I moved to location1!
I am Mister Creepy in location1.
I moved to location2!
I am Loopy Lou in location2.
I moved to ["place1", "place2"]!
I am Mister Creepy in ["place1", "place2"].
I moved to ["place1", "place2"]!
I am Loopy Lou in ["place1", "place2"].
RESP。
ArgumentError: wrong number of arguments (1 for 0)
from (irb):158:in 'each'
from (irb):158
from /usr/local/bin/irb:11:in '<main>'
如您所见,结果并不像我预期的那样。我怀疑我的期望和实际代码之间几乎没有什么区别,但我不知道它实际上是什么
PS。当您看到需要澄清或纠正的内容时,请通知我。
答案 0 :(得分:1)
boogeyman.change_location(locations)
正在将每个Boogeyman的@location
设置为整个阵列。你想要的是迭代boogeyman的对(zip
)和他的位置:
army.zip(locations).each { |boogeyman, location|
boogeyman.change_location(location)
}
答案 1 :(得分:1)
Amadan的解决方案有效,但这是另一个可能更容易理解的解决方案:
army.each_with_index { |boogeyman, idx| boogeyman.change_location(locations[idx]) }
在您当前的代码中,您将整个数组locations
传递给每个Boogeymen,因此每个数组都将其位置设置为数组["location1", "location2"]
相反,通过循环并为您循环的每个boogeyman分配locations
数组的某个索引部分,您将为每个boogeyman分配存储在数组locations
中的一个位置