Hello --
On Fri, 26 Oct 2001, Steven Thomas wrote:
>
> Another newbie question
>
> How do I get variables to use a method defined in a class.
>
> I have:
>
> class Round
> def to_hund
> @num * 100
> end
> end
>
> miles.to_hund
>
> If returns "undefined method"
That will only work if miles is an instance of class Round, which
sounds kind of illogical. In fact... "to_hund" doesn't sound like the
right name for what that method is doing. So I'm restoring some
rounding behavior to it :-) But only in a very rudimentary way. What
follows are some suggestions that you can play around with, whatever
the final version of the method turns out to be.
You could make to_hund a class method, which you can then get at
from outside in a more general way. You'd want it to take an
argument.
class Round
def Round.to_hund(num)
(num * 100.0).round / 100.0 # note: num, not @num
end # (a local variable, not
end # an instance variable)
miles = 20
p Round.to_hund(miles) # => 20.0 # probably not
# *exactly* what
# you want, but
# anyway :-)
A class method like this can be understood as a kind of utility
method, in the domain of the class but available to objects which are
not instances of the class (because, for whatever reason, other
objects might need access to the functionality in question). So in
this case you've got a class whose domain is Round-ing, and by making
to_hund a class method you've allowed objects which are not instances
of Round (such as miles, which is an Integer) to get at it.
Another possibility, and probably a more logical one: instead of a
class, write a module called Roundable. The module would define
behavior of things that can be rounded.
module Roundable
def to_hund
(self * 100.0).round / 100.0
end
end
The module on its own doesn't do anything; the idea is to mix the
module into any class for whose objects it makes sense to have a
to_hund method. Mixing into Numeric will propagate to Float and
Integer:
class Numeric
include Roundable # the "mix in"
end
p 0.009.to_hund # 0.01
p 1.to_hund # 1.0
David
--
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web: http://pirate.shu.edu/~blackdav