访问数组中的实例变量

时间:2017-05-09 17:14:38

标签: arrays ruby class instance-variables

我正在尝试访问数组中的特定值。该数组包含特定的类实例变量,如下所示:

    [[#<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>]]

我想迭代数组中的每个数组,并找出数组中有多少个传递有@type:standard。这可能吗?提前谢谢

2 个答案:

答案 0 :(得分:0)

array_of_array.inject(0) do |sum, array|
  sum + array.count { |el| el.class == Delivery && el.instance_variable_get(:@type) == :standard }
end

答案 1 :(得分:0)

您可以使用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
相关问题