我正在尝试用数字对字符串进行插值,并在迭代参与者列表时递增该数字...
字符串"Hello #{name}. You are guest number #{num}."
我知道如何迭代每个来宾名称,但是如何从1..7
的字符串中得到一个递增的数字?我知道这很简单。我是个初学者。
尝试了一切。
def assign_rooms(attendees)
room_assignments = []
rooms.to_s = [1, 2, 3, 4, 5, 6, 7]
attendees.each_with_index {|x| room_assignments<< "Hello #{x}! You'll be assigned room #{rooms}!"}
room_assignments
end
答案 0 :(得分:1)
Enumerable#each_with_index
为该块提供了两个参数:项目本身(参与者)和根据需要增加的项目索引。您也可以与Array#map
结合使用,以避免必须显式创建输出并将其附加到第二个数组。 Enumerator#with_index
允许指定索引的起始偏移量(以使房间号不从零开始)。
def assign_rooms(attendees)
attendees.map.with_index(1) {|attendee, room|
"Hello #{attendee}! You'll be assigned room #{room}!"
}
end
puts assign_rooms(['Alice', 'Bob', 'Jack'])
输出:
Hello Alice! You'll be assigned room 1!
Hello Bob! You'll be assigned room 2!
Hello Jack! You'll be assigned room 3!
答案 1 :(得分:0)
您还可以使用枚举器实现目标。假设第一个房间号是2
。
attendees = %w| Flora Billy-Bob Hank Trixie Herb |
#=> ["Flora", "Billy-Bob", "Hank", "Trixie", "Herb"]
nbr = 2.step
#=> (2.step)
nbr.is_a?(Enumerator)
#=> true
attendees.each { |name|
puts "Hello, #{name}, you've been assigned to our best room, number #{nbr.next}!" }
Hello, Flora, you've been assigned to our best room, number 2!
Hello, Billy-Bob, you've been assigned to our best room, number 3!
Hello, Hank, you've been assigned to our best room, number 4!
Hello, Trixie, you've been assigned to our best room, number 5!
Hello, Herb, you've been assigned to our best room, number 6!
请注意以下事项。
nbr.next #=> 7
nbr.next #=> 8
nbr.rewind
nbr.next #=> 2
请参见Numeric#step,Enumerator#next和(仅在您好奇的情况下)Enumerator#rewind。
答案 2 :(得分:0)
为了娱乐,我想展示一种更加结构化的方式,使用Hash作为存储信息的模型。
让我们使用这些输入数据:
rooms = [110, 111, 112, 210, 211, 212].map { |n| [n, {free: true, host: nil}] }.to_h
reception_queue = %w|Kirk Picard Spock McCoy Riker LaForge|
假设一个房间已经被预订:
rooms[210] = {free: false, host: 'Uhura'}
rooms #=> {110=>{:free=>true, :host=>nil}, 111=>{:free=>true, :host=>nil}, 112=>{:free=>true, :host=>nil}, 210=>{:free=>false, :host=>"Uhura"}, 211=>{:free=>true, :host=>nil}, 212=>{:free=>true, :host=>nil}}
现在,我们要为每个与会者分配免费房间。需要找到符合某些条件(免费,但可以是一张床,两张床,套房等)的第一个房间,具体取决于模型的复杂性。
这可以通过Enumerable#find来实现:
rooms.find { |_, v| v[:free] }
#=> [110, {:free=>true, :host=>nil}]
找到房间后,我们要在其中分配主机,将其从队列(Array#shift)中删除。如果没有匹配项,则中断循环。
reception_queue.size.times do |person|
nr = rooms.find { |_,v| v[:free] }
break unless nr
rooms[nr[0]][:host] = reception_queue.shift
rooms[nr[0]][:free] = false
end
所以您最终可以得到:
rooms #=> {110=>{:free=>false, :host=>"Kirk"}, 111=>{:free=>false, :host=>"Picard"}, 112=>{:free=>false, :host=>"Spock"}, 210=>{:free=>false, :host=>"Uhura"}, 211=>{:free=>false, :host=>"McCoy"}, 212=>{:free=>false, :host=>"Riker"}}
reception_queue #=> ["LaForge"]