def assign_rooms (array)
room_number = (1..7).to_a
attendees.map.each_with_index { |attendees, room_number|
"Hello, #{attendees}! You'll be assigned to room #{room_number}!"
}
end
答案 0 :(得分:2)
在each_with_index
块中,您已将index
值分配给本地变量room_number
。我猜你想做这样的事情:
attendees.map.with_index { |attendee, index| "Hello, #{attendee}!
You'll be assigned to room #{room_number[index]}!" }
使用此功能,您可以将每个attendee
与room_number
中与循环的index
值对应的值进行匹配。
如果您的attendees
多于room_number
,则效果不会很好。
答案 1 :(得分:0)
试试这个:
def assign_rooms (attendees)
attendees.map.with_index do |attendee, room_number|
"Hello, #{attendee}! You'll be assigned to room #{room_number + 1 }!"
end
end
array = ['steve', 'john']
p assign_rooms(array)
#=> ["Hello, steve! You'll be assigned to room 1!", "Hello, john! You'll be assigned to room 2!"]
这里我们正在映射一个新数组并使用array
的索引来制作房间号码。看到房间号码通常不会0
,我们会为每个1
添加room_number
。