1

I have a function which gets an array of element, then it iterates over the array, when expected element is found it breaks and return.

The function is this:

def get_expected_element(id:, name:)
  # I am sure there are 3 elements got
  elem_array = get_all_elements(id)

  element = nil
  elem_array.each { |elem|
    # I see this log
    puts "elem = #{elem}"

    if elem == name
      element = elem
      # I see this log too
      puts "Found element"
      break
    end
  }
  # I see this log too, and program is hanging
  puts "=== return ==="
  element
end

When I invoke the function, the program is hanging after puts "=== return ===":

service = MyService.new
element_got = service.get_expected_element(id:3, name:"apple")

# I don't see the below log
puts "#{element_got}, I don't see this, why?"

The log in console is this:

elem = orange
elem = apple
Found element
=== return ===

<it is hanging>

I cannot understand why the invoked function doesn't return?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • Have you tried an explicit return statement? (i.e. return element). I don't understand why that might make a difference but its something easy to try at first. – Dean Sep 06 '16 at 16:00
  • Yes, tried, same problem – Leem.fin Sep 06 '16 at 17:37

1 Answers1

1

Leaving out MyService I ran this:

def get_expected_element(id:, name:)
  # I am sure there are 3 elements got
  # elem_array = get_all_elements(id)
  elem_array = ["elem1", "apple", "elem3"]

  element = nil
  elem_array.each { |elem|
    # I see this log
    puts "elem = #{elem}"

    if elem == name
      element = elem
      # I see this log too
      puts "Found element"
      break
    end
  }
  # I see this log too, and program is hanging
  puts "=== return ==="
  element
end

puts get_expected_element(id: 3, name: "apple")

and got this:

elem = elem1
elem = apple
Found element
=== return ===
apple

Your get_expected_element method seems fine.

seph
  • 6,066
  • 3
  • 21
  • 19