我编写了一个程序,可以查看您是否在聚会清单上。它工作正常,但我不想添加任何内容,因此您可以选择与该方默认的五个人相比,您的聚会中有多少人。谢谢,任何帮助将不胜感激。我刚开始感到抱歉,如果我不明白。
puts "Create a party"
puts "Who is the first person: "
first_person = gets.chomp.upcase()
puts "Who is the second person: "
second_person = gets.chomp.upcase()
puts "Who is the third person: "
third_person = gets.chomp.upcase()
puts "Who is the fourth person: "
fourth_person = gets.chomp.upcase()
puts "Who is the fifth person: "
fifth_person = gets.chomp.upcase()
friends_list = Array[first_person, second_person, third_person, fourth_person, fifth_person]
puts "What is your name?"
your_name = gets.chomp.upcase()
if friends_list.include? your_name
puts "Congrats, you were invited"
else
puts "Sorry, you weren't invited. Please check with the host of the party for more details"
end
答案 0 :(得分:2)
您开始学习Ruby真是太好了!
您可以使用循环。首先创建一个数组,并将名称push
放入其中。
puts "Create a party"
puts "Enter blank if you are done"
friends_list = [] # new array
count = 1
loop do
print count.to_s + "th person's name: "
name = gets.chomp.upcase
break if name.empty?
friends_list.push(name) # add person to list
count += 1
end
puts "What is your name?"
your_name = gets.chomp.upcase()
if friends_list.include? your_name
puts "Congrats, you were invited"
else
puts "Sorry, you weren't invited. Please check with the host of the party for more details"
end
答案 1 :(得分:2)
这是方法中的分组说明示例,因此您可以重用某些内容(请参见get_name
),成为DRY。
此外,它使用哈希将人员详细信息存储到数组中。
程序一直在loop to
中运行,直到被用户输入中断为止。
def run
people = []
loop do
show_options
answer = gets.chomp.downcase.to_sym
case answer
when :a
add_person_to people
when :l
list people
when :f
find_in people
else
break
end
end
end
def show_options
puts "-"*50
puts "A: add person"
puts "L: list people"
puts "F: find person"
puts "any other key: exit"
end
def get_name
puts "Name?"
name = gets.chomp.capitalize
puts "Nickname?"
nickname = gets.chomp.capitalize
{name: name, nickname: nickname}
end
def add_person_to people
puts "Adding person nr. #{people.size + 1}"
people << get_name # check if already present?
end
def list people
puts "-"*50
people.each { |person| puts "Name: #{person[:name]} - Nickname: #{person[:nickname]}" }
puts "Total people: #{people.size}"
end
def find_in people
puts people.include? get_name # or improve
end
run # this calls the run method