converting to ints

J

Joe Van Dyk

Hi,

I have a class that could look something like this

class MyClass
attr_accessor :x, :y, :z

def math(a, b, c)
end
end

I want to be able to pass in strings to this class and have everything
converted to fixnums (or floats). Do I need to manually do the
setters for x, y, and z and convert a, b, c?

Joe
 
A

Austin Ziegler

Hi,
=20
I have a class that could look something like this
=20
class MyClass
attr_accessor :x, :y, :z
=20
def math(a, b, c)
end
end
=20
I want to be able to pass in strings to this class and have everything
converted to fixnums (or floats). Do I need to manually do the
setters for x, y, and z and convert a, b, c?

Yes.

-austin
--=20
Austin Ziegler * (e-mail address removed)
* Alternate: (e-mail address removed)
 
J

Joe Van Dyk

=20
Yes.
=20

Wondering if it would be useful to have functions like
attr_accessor_int :a_int, :another_int
attr_accessor_string :a_string=20

and then dynamically create the following methods

def a_int=3D(x); @a_int =3D x.to_int; end
def another_int=3D(x); @another_int =3D x.to_int; end
def a_string=3D(x); @a_string =3D x.to_s; end;
 
J

Joel VanderWerf

Joe said:
Wondering if it would be useful to have functions like
attr_accessor_int :a_int, :another_int
attr_accessor_string :a_string

and then dynamically create the following methods

def a_int=(x); @a_int = x.to_int; end
def another_int=(x); @another_int = x.to_int; end
def a_string=(x); @a_string = x.to_s; end;

You might want to use #to_i rather than #to_int, so that strings are
converted. Or maybe not, depending on what you want...

irb(main):001:0> "1".to_int
NoMethodError: undefined method `to_int' for "1":String
from (irb):1
irb(main):002:0> "1".to_i
=> 1
 
J

Joe Van Dyk

Joe Van Dyk wrote:
=20
=20
You might want to use #to_i rather than #to_int, so that strings are
converted. Or maybe not, depending on what you want...
=20
irb(main):001:0> "1".to_int
NoMethodError: undefined method `to_int' for "1":String
from (irb):1
irb(main):002:0> "1".to_i
=3D> 1

Yes, you're right. Brain fart on my part.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,498
Latest member
log5Sshell/alfa5

Latest Threads

Top