0

I am trying to implement Integer#times, but don't know how to know the value of an Integer object. So I am doing it like this:

class Integer
  def times
    n = (self.next) -1
    x = 1
    while x <= n
      yield(x)
      x += 1
    end
  end
end

I am using (self.next) -1 to get the value of the object:) I know it is not the right way of doing it. How to get the value of the Integer object?

2
  • thanks. that works. i was thinking about that but didn't try, i thought self is object. i am confused about the object and it's value. Commented Apr 6, 2015 at 6:16
  • The value of an integer is that same integer. x = 1; x.equal?(x.to_i) is true. In fact, the definition of Integer#to_i is static VALUE int_to_i(VALUE num) { return num; } (equivalent to def to_i; self; end in Ruby). Commented Apr 6, 2015 at 6:31

1 Answer 1

1

you can just use self as mentioned by messanjah.

Note: if you try object.methods in ruby console for an int like 5.methods, you can find all the methods the object supports like to_i and to_int which also returns the value of the int object so, you can try self.to_int

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.