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?
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
It's not completely clear what you want.
If you want to be able to convert an instance of String to_i, then just call to_i:
"75%".to_i => 75
If you want it to have some special behavior, then monkey patch the String class:
class String
def percentage_to_i
self.to_i # or whatever you want
end
end
And if you truly want to chain methods, then you typically want to return a modified instance of the same class.
class String
def half
(self.to_f / 2).to_s
end
end
s = "100"
s.half.half => "25"
Singleton methods
def percentage.percentage_to_i
self.chomp('%')
self.to_i
end
creating your own class
class Percent
def initialize(value)
@value = value
end
def to_i
@value.chomp('%')
@value.to_i
end
def to_s
"#{@value}%"
end
end