Home > Software engineering >  How do I extract these values from a Ruby array
How do I extract these values from a Ruby array

Time:10-05

I'm debugging some Ruby code that uses the AWS SDK to extract EC2 tags:

         resource = Aws::EC2::Resource.new(client: client)

         resource.instances({filters: fetch(:ec2_filters)}).each do |instance|
           puts "DEBUG: #{instance.tags}"
           app_tag = instance.tags.select { |t| t.key == 'application' }.pop.value

We recently updated the jmespath dependency to pick up this change.

BEFORE updating:

DEBUG: [#<struct Aws::EC2::Types::Tag key="application", value="api">, #<struct Aws::EC2::Types::Tag key="environment", value="production">]

AFTER updating jmespath

DEBUG: [{:key=>"application", :value=>"api"}, {:key=>"environment", :value=>"production"}]

The .select { |t| t.key == 'application' }. now throws an error:

ArgumentError: wrong number of arguments (given 0, expected 1)

Can anyone advise how to parse the new response format? (i.e. [{:key=>"application", :value=>"api"}...)

UPDATE 1

# This finds the correct item, but I'm not sure how to extract ':value'
puts "DEBUG: #{instance.tags.select { |t| t[:key] == 'application' }}"


DEBUG: [{:key=>"application", :value=>"api"}]

UPDATE 2

This works:

puts "DEBUG: #{instance.tags.select { |t| t[:key] == 'application' }[0][:value]}"

DEBUG: api

CodePudding user response:

Before the change the value of instance.tags used to be a struct, where you can access the key attribute by using dot notation, now you have a hash so you can use :[] instead, e.g:

Struct.new(:key).new('hej').key # "hej"
({ key: 'hej' })[:key]          # "hej"
  •  Tags:  
  • ruby
  • Related