rubyruby-2.6

Ruby returns early from loop


I have a class, with one method:

class ScreenerProbe 
  def initialize
    @body = {}
  end

  def import_simple_matrix(questions, answers)    
    @body['aliases'] = answers.map { |pair| 
      return { val: pair["text"], text: pair["value"] }
    }
    
    # this code doesn't seem to run
    questions.each.with_index do |text, index|
      @body["questions"][index + 1] = {
        "title" => text,
        "type" => 'default',
      }
    end
end

The problem is that some of the code doesn't seem to run, even though I expect it to.

ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-darwin20]


Solution

  • When calling return from inside a loop, it won't only "exit" the loop, you will return from the outer method, in this case import_simple_matrix.

    This is probably not what you want, and the reason why some assignments, that you're expecting, won't occur.