我正在做一个项目,其中最终结果必须包含由不同方法(batch_badge_creator和assign_rooms)生成的两个数组的主列表。
我的问题在于最后一节,即打印机方法。我需要在屏幕上输出两种方法,并分别打印出每个数组的每个数组项。
如何迭代房间分配数组以便分出每个单独的作业?
感谢您的帮助!
def badge_maker(name)
"Hello, my name is #{name}."
end
attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
def batch_badge_creator(attendees)
attendees.each {|x| badge_maker(x)}
return badges
end
def assign_rooms(room)
room = [1, 2, 3, 4, 5, 6, 7]
attendees.each_with_index {|x, index| "Hello #{attendees}! You will be assigned to room #{room}!"}
return room_assignments
end
def printer(attendees)
assign_rooms.each {|x| puts batch_badge_creator(assign_rooms)}
puts badges_and_room_assignments
end
我需要打印机才能这样做:
Hello, my name is Edsger.
Hello, my name is Ada.
Hello, my name is Charles.
Hello, my name is Alan.
Hello, my name is Grace.
Hello, my name is Linus.
Hello, my name is Matz.
Hello, Edsger! You'll be assigned to room 1!
Hello, Ada! You'll be assigned to room 2!
Hello, Charles! You'll be assigned to room 3!
Hello, Alan! You'll be assigned to room 4!
Hello, Grace! You'll be assigned to room 5!
Hello, Linus! You'll be assigned to room 6!
Hello, Matz! You'll be assigned to room 7!
答案 0 :(得分:1)
好的,我已经做了一些改进,但我认为这就是你所追求的。密切关注以@
开头的变量。这些是实例变量,简而言之,它们本身可以被同一个类中的其他方法看到。我还把所有东西放在一个类中,只是一些整体整理并添加了一些新的位。希望它有用。
class HotelEvent
def badge_maker(name)
"Hello, my name is #{name}."
end
def attendees
@attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
end
def batch_badge_creator
@badges = @attendees.map {|x| badge_maker(x)}
end
def assign_rooms
@room_assignments = @attendees.map.with_index {|attendee, room| "Hello #{attendee}! You will be assigned to room #{room+1}!"}
end
def print_badges
@badges.each {|b| puts b}
end
def print_room_numbers
@room_assignments.each {|r| puts r}
end
def print_all
print_badges
print_room_numbers
end
end
new_event = HotelEvent.new
new_event.attendees
new_event.batch_badge_creator
new_event.assign_rooms
new_event.print_all
输出将是:
Hello, my name is Edsger.
Hello, my name is Ada.
Hello, my name is Charles.
Hello, my name is Alan.
Hello, my name is Grace.
Hello, my name is Linus.
Hello, my name is Matz.
Hello Edsger! You will be assigned to room 1!
Hello Ada! You will be assigned to room 2!
Hello Charles! You will be assigned to room 3!
Hello Alan! You will be assigned to room 4!
Hello Grace! You will be assigned to room 5!
Hello Linus! You will be assigned to room 6!
Hello Matz! You will be assigned to room 7!
只需编辑和修改您的口味!请记住,代码仍然可以得到很大改善。例如,通过添加一些setter方法,但我会把它作为练习留给你。祝你好运。