Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
Dru Avatar asked Feb 20 '23 16:02

Dru


1 Answers

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
like image 176
Mischa Avatar answered Mar 07 '23 16:03

Mischa