To_i vs. to_int

Hello,

I have a class which instances can be represented as integers. What is
the difference between the to_i and to_int methods, and when is which
form needed ?

Ico

Ico ha scritto:

Hello,

I have a class which instances can be represented as integers. What is
the difference between the to_i and to_int methods, and when is which
form needed ?

short names (to_x) are for common programmer use.
Long names (to_xyz) are there so that ruby can do some implicit
conversions between things that can basically be threated as xyz.

So in your case it could be meaningful to define one and alias the other
to it.

Hi –

On Sun, 30 Jul 2006, gabriele renzi wrote:

So in your case it could be meaningful to define one and alias the other to
it.

What’s a use case for to_int? I was thinking of this classic to_str
example:

class S
def to_str
“some text”
end
end

puts "Here is " + S.new # Here is some text

But the to_int equivalent doesn’t work:

class S
def to_int
2
end
end

puts 2 + S.new # TypeError: S can’t be coerced into Fixnum

Same thing with:

puts Integer(2) + S.new

I’m stuck trying to find a case where to_int does what to_str does –
but maybe it doesn’t.

David

“d” == dblack [email protected] writes:

d> class S
d> def to_int
d> 2
d> end
d> end

d> puts 2 + S.new # TypeError: S can’t be coerced into Fixnum

  puts 2 | S.new

Guy Decoux

Hi –

On Sun, 30 Jul 2006, ts wrote:

 puts 2 | S.new

Interesting. What’s the rationale for not doing the conversion for +
and - and other operator/methods?

David

On Jul 29, 2006, at 12:58 PM, [email protected] wrote:

Same thing with:

puts Integer(2) + S.new

I’m stuck trying to find a case where to_int does what to_str does –
but maybe it doesn’t.

However,

puts 2 + Integer(S.new) => 4

uses your S#to_int

Regards, Morton

[email protected] ha scritto:

 puts 2 | S.new

also, Arrays seem to like it:

a=Object.new
=> #Object:0x2c103a0

def a.to_int() 2 end
=> nil

[0,1,3][a]
=> 3

Array.new(a){ 0 }
=> [0, 0]

Interesting. What’s the rationale for not doing the conversion for +
and - and other operator/methods?

I’d like to know the same :slight_smile:

We actually gabbed on this topic a bit recently. See the second half
of the “Symbols are your friends” thread from a couple of days ago.

Hi –

On Sun, 30 Jul 2006, Morton G. wrote:

puts 2 + S.new # TypeError: S can’t be coerced into Fixnum
puts 2 + Integer(S.new) => 4

uses your S#to_int

True, but it works the same with to_i, as opposed to the string one
where to_s and to_str work differently.

David

Aleks Kissinger ha scritto:

We actually gabbed on this topic a bit recently. See the second half
of the “Symbols are your friends” thread from a couple of days ago.

Oh, I missed this, thank you

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs