函数不返回,很奇怪



我有一个函数,它获得一个元素数组,然后在数组上迭代,当找到预期的元素时,它中断并返回。

函数是这样的:

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

当我调用函数时,程序在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?"

登录控制台如下:

elem = orange
elem = apple
Found element
=== return ===
<it is hanging>

我不明白为什么调用的函数不返回?

省略MyService我运行了这个:

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")

得到了这个

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

你的get_expected_element方法看起来不错。

相关内容

  • 没有找到相关文章

最新更新