Home > database >  Cleanest way to iterate through a loop in Ruby, while outputting two values?
Cleanest way to iterate through a loop in Ruby, while outputting two values?

Time:11-26

I have a simple loop, which is fed an Array with multiple elements, the goal of my function is to iterate over each element, with the value of ID to be the same as the ID of the element currently in the loop and the value of 'body' to be that of the entire same element.

I'm struggling to ensure that the loop resets and feeds in a new element every iteration, rather than one or the other remaining in the loop.

What would be the best way to achieve this?

@data = [{ 'url' => 'https://zendesk.com/api/v2/macros/1900002708354.json',
           'id' => 1_900_002_708_354,
           'actions' => [{ 'field' => 'comment_value_html', 'value' => '{{email}} 360081752739' }],
           'restriction' => nil },
         { 'url' => 'https://zendesk.com/api/v2/macros/360081752739.json',
           'id' => 360_081_752_739,
           'actions' => [{ 'field' => 'comment_value_html', 'value' => '{{IBAN}} ' }],
           'restriction' => nil },
         { 'url' => 'https://zendesk.com/api/v2/macros/360081755559.json',
           'id' => 360_081_755_559,
           'actions' => [{ 'field' => 'comment_value_html', 'value' => '{{email}} 360081752739' }],
           'restriction' => nil }]





def run_function
  @data.each do |x|
    @id = [x.select { |m| m['id'] }]
    final_data = x
    body = final_data
    puts body
  end
 end

My ID variable currently outputs as [{"id"=>1900002708354}], whereas I only require the number.

CodePudding user response:

@data.each do |hash|
  id = hash['id']
  puts id
end
  • Related