4

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?

1
  • 1
    Why not make a Percent class? Commented Apr 28, 2012 at 2:27

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

Haha I ended up doing this and coming back to write my own answer. Waiting to accept yours. Thanks.
Thanks, the question was more about chaining but I did not know that I could do the same thing with to_i alone.
I added the method to the String class (as in your answer), but in a model file (app/models/content.rb), after that model's class definition's end statement. I think doing so is called "mixin".
1

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"

Comments

0

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

3 Comments

Interesting, when would this be more advantageous than extending the class? I'm trying to figure out a use-case for the extra work involved with Singleton methods?
@Dru Singleton methods on instances are useful when they're one-off things. I've used them when I need to morph an object to an API for use in a library function, but they're not needed very often.
When there is actually only one instance that you need a different behavior that's not defined in the class. The good thing about it is that you don't have to change the class nor extending it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.