Robin van Dijk
Robin van Dijk

Reputation: 827

Accessing loop variable in other methods

Let's say I have the following method:

def run
  @users.each do |u|
    ..
    ..
  end
end

I have a lot of code in run so I am trying to refactor it and splitting it up into smaller methods. One of these methods is the following:

def finish_mutation
  ..
  ..
  Rails.logger.info "Succesfully added #{u.name}"
end

This breaks because finish_mutation doesn't have access to the u variable. How can I create new methods that can access the u variable that I created in run?

Upvotes: 1

Views: 58

Answers (3)

Will
Will

Reputation: 845

Sometimes passing your loop variable (as shown in the other answers) is the best answer. Sometimes you can DRY things up better by adding a method to whatever class 'u' is an instance of. So you might do

class User
def finish_mutation
 # put your operation here
end
end 

And then in your loop

u.finish_mutation

Obviously you need to think about which is the best way for a specific case.

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

You can simply create method taking parameter:

def finish_mutation(user)
  # code
  Rails.logger.info "Successfully added #{user.name}"
end

and call it, passing User instance:

finish_mutation(u)

Upvotes: 4

medBouzid
medBouzid

Reputation: 8372

it's easy to do you just add a parameter to your finish_mutation method like this :

def finish_mutation(param)
   # .......
end

then you call your function like this :

def run
  @users.each do |u|
    ..
    ..

    finish_mutation(u)  # <----- for example here you call your method

  end
end

Upvotes: 3

Related Questions