Search code examples
rubychainingmethod-chaining

Ruby Method Chaining


I would like to chain my own methods in Ruby. Instead of writing ruby methods and using them like this:

def percentage_to_i(percentage)
  percentage.chomp('%')
  percentage.to_i
end

percentage = "75%"
percentage_to_i(percentage)
=> 75

I would like to use it like this:

percentage = "75%"
percentage.percentage_to_i
=> 75

How can I achieve this?


Solution

  • You have to add the method to the String class:

    class String
      def percentage_to_i
        self.chomp('%')
        self.to_i
      end
    end
    

    With this you can get your desired output:

    percentage = "75%"
    percentage.percentage_to_i # => 75
    

    It's kind of useless, because to_i does it for you already:

    percentage = "75%"
    percentage.to_i # => 75