我正在尝试使用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)
]
I tried:
high_capacities_homes = homes.select do |hm|
hm.capacity >= 4
puts high_capacities_homes
end
没有任何成功,我没有想法,有人可以帮助吗?(
Try
high_capacities_homes = homes.select do |hm|
hm.capacity >= 4
end
puts high_capacities_homes
puts
返回nil,因此您的所有块计算为false。
让我们仔细看看发生了什么。当你执行你的代码时,你会得到以下内容:
high_capacities_homes = homes.select do |hm|
hm.capacity >= 4
puts high_capacities_homes
end
=> []
返回一个空数组,但是为什么所有这些空行?这是因为您的代码对homes
的每个元素执行puts nil
。想想看:
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
的元素。
您是否希望创建一个包含homes
和hm.capacity >= 4
的元素hm
的数组(以及打印这些实例的信息)?如果是,首先选择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保留homes
的所有hm
元素,select
的block返回true
。
现在,你想打印什么?如果它是selected_homes
的每个元素的实例变量的值,您可以这样做(作为一个示例)。
selected_homes.each { |hm|
puts "#{hm.name} in #{hm.city} has capacity #{hm.capacity} and price $#{hm.price}" }
打印
Fernando's place in Seville has capacity 5 and price $47
Ariel's place in San Juan has capacity 4 and price $49
1当然,你也可以写成selected_homes = homes.reject { |hm| hm.capacity < 4 }
.