0

I want to add new method to Integer class, but I have no idea how to access integer value in this method:

class Integer
  def foo
    'foo' * value
  end
end

It should work like:

3.foo
=> 'foofoofoo'
2
  • This is not particular to integers, by the way. self always references the receiver, not just in integers. Commented Oct 9, 2017 at 20:10
  • @zerozero7 I have updated my answer. It may be of interest. Commented Dec 5, 2017 at 1:12

1 Answer 1

5

Using self:

class Integer
  def foo
    'foo' * self
  end
end
#It should work like:

p 3.foo
#=> 'foofoofoo'

You can also use Kernel#__method__ for a more general approach:

class Integer
  def foo
    __method__.to_s * self
  end
end

p 3.foo
#=> 'foofoofoo'
Sign up to request clarification or add additional context in comments.

Comments

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.