ToddT
ToddT

Reputation: 3258

Dynamically call a method based on a variable name

I have an app that calculates shipping costs based on the "speed" a user selects. I'm trying to refactor this if statement based on those speeds. This is the current if statement:

  def walk_thru_each_rate_type(speed_hash, speed_from_db)
    if speed_hash.has_key?("flex")
      handle_flex_rates(speed_from_db)
    end
    if speed_hash.has_key?("fixed")
      handle_fixed_rates(speed_from_db)
    end
    if speed_hash.has_key?("free")
      handle_free_shipping(speed_from_db)
    end
  end

So each method is just based on the "speed". flex, fixed or free and the method names have those speeds in them. I was thinking something like this, but it doesn't work:

handle_"#{speed}"_rates(speed_from_db)

How can I dynamically call my method based on the speed name?

Upvotes: 0

Views: 47

Answers (1)

Tiago Farias
Tiago Farias

Reputation: 3407

You can call Object#send passing the method name and the params. In your case, it would be like:

self.send("handle_#{speed}_rates", speed_from_db)

Take a look at https://apidock.com/ruby/Object/send

Upvotes: 2

Related Questions