0

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.

9
  • For the love of god, please indent the code properly. Otherwise the code becomes impossible to scan. Commented Nov 25, 2021 at 20:37
  • In this particular case, the body of the each should be indented by one level. Commented Nov 25, 2021 at 20:38
  • 1
    @SergioTulentsev Ok. Correct? Commented Nov 25, 2021 at 20:41
  • Perfect. Now, I have questions about the code. Not sure what you attempted to do with @data.select { |m| m['actions'] }.map { |m| m['id'] }, but it most certainly is not doing what you think it does. It'll have the same value (a list of all ids) at each iteration. In particular, .select { |m| m['actions'] } is useless (given the provided input array) Commented Nov 25, 2021 at 20:43
  • 1
    @cbin1 : Since @data is an array of Hashes, x must be a Hash. What's the point in applying select to a Hash? Commented Nov 26, 2021 at 8:36

1 Answer 1

1
@data.each do |hash|
  id = hash['id']
  puts id
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.