我需要为每个人分配一个房间号,但它会为每个人分配一个房号

时间:2016-03-26 21:30:37

标签: ruby

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

2 个答案:

答案 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]}!" }

使用此功能,您可以将每个attendeeroom_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