Home > Net >  Ruby only allow one iteration in my method
Ruby only allow one iteration in my method

Time:02-02

I have a class, with one method:

class ScreenerProbe 
  def initialize
    print "Initializing new ProbeObject"
    @body = YAML.load(File.open("#{__dir__}/screener_template.yaml"))
  end

  def import_simple_matrix(questions_array, answers_array)    
    @body["rules"]["total"] = (1..questions_array.count).to_a.to_s
    @body['comment'] = "!REMOVE quotations for each rule. "
    @body['aliases'] = answers_array.map { |pair| 
      return { val: pair["text"], text: pair["value"] }
    }

    questions_array.each.with_index do |text, index|
      @body["questions"][index 1] = {
        "title" => text,
        "type" => 'default',
        "options" => '*1'
      }
    end
end

The problem is with the two iterations in import_simple_matrix,

  1. @body['aliases'] = answers_array.map{|pair| return {val: pair["text"], text: pair["value"]} }
  2. questions_array.each.with_index do |text, index|

When I run this in the current order, only @body['aliases'] gets assigned new values. But when I move 1. below 2., only @body["questions"] gets assigned new values.

So it seems I can't run two iterations in the same method?

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

CodePudding user response:

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.

  •  Tags:  
  • Related