How to find the key of the last array

  • A+
Category:Languages

I have a hash that has an array value:

some_attributes['variants'] # => # [ #   [["variantCode", "0715839001002"], ["sizeCode", "002"], ["sizeName", "XS"]], #   [["variantCode", "0715839001003"], ["sizeCode", "003"], ["sizeName", "S"]], #   [["variantCode", "0715839001004"], ["sizeCode", "004"], ["sizeName", "M"]], #   [["variantCode", "0715839001005"], ["sizeCode", "005"], ["sizeName", "L"]] # ] 

I am expecting in a new array the keys of each "sizeName":

['XS', 'S', 'M', 'L'] 

I tried like this:

some_attributes['variants'[[['sizeName']]]]  some_attributes['variants'].select{|size| sizeName["sizeName"]} 

But I can't find the solution. Any tricks?

 


Looks like you could turn the variants into hashes.

some_attributes = {   "variants" => [     [["variantCode", "0715839001002"], ["sizeCode", "002"], ["sizeName", "XS"]],     [["variantCode", "0715839001003"], ["sizeCode", "003"], ["sizeName", "S"]],     [["variantCode", "0715839001004"], ["sizeCode", "004"], ["sizeName", "M"]],     [["variantCode", "0715839001005"], ["sizeCode", "005"], ["sizeName", "L"]]   ] }  variants = some_attributes['variants'].map(&:to_h) variants.map { |variant| variant['sizeName'] } => ["XS", "S", "M", "L"] 

Then it's easier to do something like:

large_variant = variants.find { |variant| variant['sizeName'] == 'L' } puts large_variant['variantCode'] # outputs: # 0715839001005 

Or to just get what you wanted, simply:

some_attributes['variants'].map { |a| a.last.last } #=> ["XS", "S", "M", "L"] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: