简体   繁体   中英

Accessing instance variables inside an array

I am trying to access a specific value inside an array. The array contains specific class instance variables and is as follows:

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

I want to iterate over each array inside the array and find out how many Delivery's within the array have @type:standard. Is this possible? Thank you in advance

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

You can use select() to filter the elements of an array.

Reconstructing your data:

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

Filtering the array with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM