我得到This loop will have at most one iteration
以下代码块。但是当我添加else条件时,我得到了一个错误
def self.list_all_rentals_person_id(people, rentals)
list_all_people(people)
print 'ID of person: '
person_id = gets.chomp
rentals.each do |rental|
return puts "Rentals:nDate: #{rental.date} Book: #{rental.book.title}" if rental.person.id == person_id
else
return puts 'No Rental Records Found'
end
end
但是当我只使用if和return时,if条件返回。我不会得到任何错误
def self.list_all_rentals_person_id(people, rentals)
list_all_people(people)
print 'ID of person: '
person_id = gets.chomp
rentals.each do |rental|
return puts "Rentals:nDate: #{rental.date} Book: #{rental.book.title}" if rental.person.id == person_id
end
end
已经提供了您所做的错误的解释。
然而,你似乎真的想要Enumerable#find
。
irb(main):001:0> a = [[4, 5], [2, 9], [7, 6]]
irb(main):002:1* if b = a.find { |x| x[0] > 6 }
irb(main):003:1* p b
irb(main):004:1* else
irb(main):005:1* puts "Nothing found"
irb(main):006:0> end
[7, 6]
=> [7, 6]
将此翻译为您的案例:
def self.list_all_rentals_person_id(people, rentals)
list_all_people(people)
print 'ID of person: '
person_id = gets.chomp
if rental = rentals.find { |rental| rental.person.id == person_id }
puts "Rentals:nDate: #{rental.date} Book: #{rental.book.title}"
else
puts 'No Rental Records Found'
end
end
或者您可能想要使用Enumerable#select
来获得所有符合您的标准的租赁。
def self.list_all_rentals_person_id(people, rentals)
list_all_people(people)
print 'ID of person: '
person_id = gets.chomp
matching_rentals = rentals.select { |r| r.person.id == person_id }
if matching_rentals.empty?
puts 'No Rental Records Found'
else
puts "Rentals:"
matching_rentals.each do |rental|
puts "Date: #{rental.date} Book: #{rental.book.title}"
end
end
end
看看你的代码,你有很多小错误。
首先,Rubocop在循环的第一次迭代时直接报错,因为return将结束循环。如果在循环后移动返回值,它将循环直到找到第一个结果。
def self.list_all_rentals_person_id(people, rentals)
list_all_people(people)
print 'ID of person: '
person_id = gets.chomp
rentals.each do |rental|
return puts "Rentals:nDate: #{rental.date} Book: #{rental.book.title}" if rental.person.id == person_id
end
puts 'No Rental Records Found'
end
(注意:如果你想在ruby中返回函数的最后一条语句,你可以去掉return,因为它总是返回值)
您的另一个问题是您不能将单行if语句return foo if bar
与第二行else组合在一起。
return puts "Rentals:nDate: #{rental.date} Book: #{rental.book.title}" if rental.person.id == person_id
else
return puts 'No Rental Records Found'
end
应该写成
if rental.person.id == person_id
return puts "Rentals:nDate: #{rental.date} Book: #{rental.book.title}"
else
return puts 'No Rental Records Found'
end
但是,在这种情况下,Rubocop不会满意。