我尝试使用select来获取容量> = 4:
class Home
attr_reader(:name, :city, :capacity, :price)
def initialize(name, city, capacity, price)
@name = name
@city = city
@capacity = capacity
@price = price
end
end
homes = [
Home.new("Nizar's place", "San Juan", 2, 42),
Home.new("Fernando's place", "Seville", 5, 47),
Home.new("Josh's place", "Pittsburgh", 3, 41),
Home.new("Gonzalo's place", "Málaga", 2, 45),
Home.new("Ariel's place", "San Juan", 4, 49)
]
我试过了:
high_capacities_homes = homes.select do |hm|
hm.capacity >= 4
puts high_capacities_homes
end
没有任何成功和我的想法,有人可以帮忙吗? :(
答案 0 :(得分:3)
尝试
high_capacities_homes = homes.select do |hm|
hm.capacity >= 4
end
puts high_capacities_homes
puts
返回nil,因此所有块都评估为false。
答案 1 :(得分:1)
让我们仔细看看发生了什么。执行代码时,您将获得以下内容。
high_capacities_homes = homes.select do |hm|
hm.capacity >= 4
puts high_capacities_homes
end
=> []
返回一个空数组,但为什么所有这些空行?这是因为您的代码正在为puts nil
的每个元素执行homes
。考虑一下:
high_capacities_homes = homes.select do |hm|
hm.capacity >= 4
puts "high_capacities_homes is nil: #{high_capacities_homes.nil?}"
end
high_capacities_homes is nil: true
high_capacities_homes is nil: true
high_capacities_homes is nil: true
high_capacities_homes is nil: true
high_capacities_homes is nil: true
=> []
当Ruby看到
时high_capacities_homes = <anything>
她做的第一件事是创建一个局部变量high_capacities_homes
并为其赋值nil
。只有在select
完成枚举homes
后,high_capacities_homes
才会为select
块的返回值指定,即[]
。
还有另一个问题。方法的第一行,
hm.capacity >= 4
返回true
或false
,但不会对该返回值执行操作。就好像它刚刚被射入太空,永远不会被再次看到,使你的代码等同于:
high_capacities_homes = homes.select do |hm|
puts high_capacities_homes
end
由于puts返回nil
(在打印任何打印之后),为了构造数组high_capacities_homes
,您的代码相当于:
high_capacities_homes = homes.select do |hm|
nil
end
这就是为什么没有选择homes
的元素的原因。
您是否希望为hm
创建homes
元素hm.capacity >= 4
的数组(以及有关这些实例的打印信息)?如果是这样,首先选择您想要的homes
元素: 1 。
selected_homes = homes.select { |hm| hm.capacity >= 4 }
# => [#<Home:0x007ff81981e138 @name="Fernando's place", @city="Seville",
# @capacity=5, @price=47>,
# #<Home:0x007ff81981dda0 @name="Ariel's place", @city="San Juan",
# @capacity=4, @price=49>]
请注意,Array#select会保留hm
阻止homes
的所有select
元素{。}}。
现在,您想要打印什么?如果它是true
的每个元素的实例变量的值,您可以按照以下方式执行此操作(作为示例)。
selected_homes
打印
selected_homes.each { |hm|
puts "#{hm.name} in #{hm.city} has capacity #{hm.capacity} and price $#{hm.price}" }
1当然,您可以写Fernando's place in Seville has capacity 5 and price $47
Ariel's place in San Juan has capacity 4 and price $49
。