R
Robert William Vesterman
Is there a way to force an attr_writer to store its input as a certain
type?
For example, I'm reading records out of a text file, splitting them
into fields, and setting various members of a class from those fields.
Some of the fields are intended to be floating point numbers. But
since they are read as strings, if I do something like:
attr_writer :blah
I'm stuck with them as strings. Obviously I can get around this by
changing it to a float before calling the attr_writer:
bling.blah = input.to_f
But rather than put a bunch of "to_f" calls all over the place, it
seems that it would be easier, cleaner, and safer to let me do
something along the lines of:
attr_writer :blah { |input| input.to_f }
I understand that's not valid syntax - what I mean by it is "when
something tries to write to blah to a value, set blah to the results
of calling to_f on the value".
I also understand that I can manually write a "def blah=", but
attr_writer is much more succinct.
Is there a nice way to do that?
Thanks in advance for any help.
Bob Vesterman.
type?
For example, I'm reading records out of a text file, splitting them
into fields, and setting various members of a class from those fields.
Some of the fields are intended to be floating point numbers. But
since they are read as strings, if I do something like:
attr_writer :blah
I'm stuck with them as strings. Obviously I can get around this by
changing it to a float before calling the attr_writer:
bling.blah = input.to_f
But rather than put a bunch of "to_f" calls all over the place, it
seems that it would be easier, cleaner, and safer to let me do
something along the lines of:
attr_writer :blah { |input| input.to_f }
I understand that's not valid syntax - what I mean by it is "when
something tries to write to blah to a value, set blah to the results
of calling to_f on the value".
I also understand that I can manually write a "def blah=", but
attr_writer is much more succinct.
Is there a nice way to do that?
Thanks in advance for any help.
Bob Vesterman.