Goalie
Goalie

Reputation: 3105

What are the benefits of using send in Ruby on Rails?

I've noticed in the code that I'm working on that send has been used frequently and I don't completely understand it. What the benefits of using it instead of not complicating things and not using it?

An example:

  def star_ratings_count(rating)
    self.send("#{rating}_ratings".to_sym).star.count
  end

  def update_star_ratings_count
    self.ratings_count = star_ratings_count(:criteria_one_rating)
  end

Upvotes: 2

Views: 1028

Answers (1)

Nick Kugaevsky
Nick Kugaevsky

Reputation: 2945

There could be many situations when using send is preferable. Some of them (which I met by myself) below

  1. When you don't know real method name. Like in your example.
  2. With send you can call private or protected methods. So you can use it in testing these methods from outside tested model.
  3. When you want to call methods in loop. Something like this

    [:method1, :method2].each { |method| object.send(method) }

Upvotes: 8

Related Questions