[英]Accessing instance variables inside an array
我试图访问数组内的特定值。 该数组包含特定的类实例变量,如下所示:
[[#<Supermarket:0x007f8e989daef8 @id=1, @name="Easybuy">,
#<Delivery:0x007f8e989f98a8 @type=:standard, @price=5.0>],
[#<Supermarket:0x007f8e99039f88 @id=2, @name="Walmart">,
#<Delivery:0x007f8e989f98a8 @type=:standard, @price=5.0>],
[#<Supermarket:0x007f8e9901a390 @id=3, @name="Forragers">,
#<Delivery:0x007f8e989eae20 @type=:express, @price=10.0>]]
我想遍历该数组中的每个数组,并找出该数组中有多少个Delivery具有@type:standard。 这可能吗? 先感谢您
array_of_array.inject(0) do |sum, array|
sum + array.count { |el| el.class == Delivery && el.instance_variable_get(:@type) == :standard }
end
您可以使用select()过滤数组的元素。
重建数据:
require 'ostruct'
require 'pp'
supermarket_data = [
['Easybuy', 1],
['Walmart', 2],
['Forragers', 3],
]
supermarkets = supermarket_data.map do |(name, id)|
supermarket = OpenStruct.new
supermarket.name = name
supermarket.id = id
supermarket
end
delivery_data = [
['standard', 5.0],
['standard', 5.0],
['express', 10.0],
]
deliveries = delivery_data.map do |(type, price)|
delivery = OpenStruct.new
delivery.type = type
delivery.price = price
delivery
end
combined = supermarkets.zip deliveries
pp combined
[[#<OpenStruct name="Easybuy", id=1>,
#<OpenStruct type="standard", price=5.0>],
[#<OpenStruct name="Walmart", id=2>,
#<OpenStruct type="standard", price=5.0>],
[#<OpenStruct name="Forragers", id=3>,
#<OpenStruct type="express", price=10.0>]]
用select()
过滤数组:
standard_deliveries = combined.select do |(supermarket, delivery)|
delivery.type == 'standard'
end
pp standard_deliveries # pretty print
p standard_deliveries.count
[[#<OpenStruct name="Easybuy", id=1>,
#<OpenStruct type="standard", price=5.0>],
[#<OpenStruct name="Walmart", id=2>,
#<OpenStruct type="standard", price=5.0>]]
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.