Hi,
let's say I've got a class Point2D to write, it must have 2 methods to
initialize :
1. one with cartesian coordinates i.e : p = Point2D.new(x,y) given the
numbers x and y;
2. a second with polar coordinates i.e : p = Point2D.new(R,theta) given
the radius R>0 and an angle theta;
How can I manage this ?
Hi,
let's say I've got a class Point2D to write, it must have 2 methods to
initialize :
1. one with cartesian coordinates i.e : p = Point2D.new(x,y) given the
numbers x and y;
2. a second with polar coordinates i.e : p = Point2D.new(R,theta) given
the radius R>0 and an angle theta;
How can I manage this ?
One way would be to take keyword arguments and figure out which you were
given.
class Point2D
def initialize( params )
if params.has_key? :r and params.has_key? :theta
## initialize from polar
elsif params.has_key? :x and params.has_key? :y
## initialize from cartesian
else
raise ArgumentError.new( "You must provide either :r and :theta OR
:x and :y" )
end
end
end
One way would be to take keyword arguments and figure out which you were given.
class Point2D
def initialize( params )
if params.has_key? :r and params.has_key? :theta
## initialize from polar
elsif params.has_key? :x and params.has_key? :y
## initialize from cartesian
else
raise ArgumentError.new( "You must provide either :r and :theta OR :x and :y" )
end
end
end
What you've proposed is a fine idea, but I think that it's important to be clear about your terminology. Ruby doesn't currently have keyword arguments. In the example that you've provided you are passing a hash with symbols for keys into the initialize method and _not_ using keywords.
Quoting Mike Fletcher <lemurific+rforum@gmail.com>:
kibleur.christophe wrote:
> Hi,
> let's say I've got a class Point2D to write, it must have 2
methods to
> initialize :
> 1. one with cartesian coordinates i.e : p = Point2D.new(x,y)
given the
> numbers x and y;
> 2. a second with polar coordinates i.e : p =
Point2D.new(R,theta) given
> the radius R>0 and an angle theta;
> How can I manage this ?
If you are always storing cartesian coordinates internally, I'd
suggest introducing a different factory method for creating points
from polar coordinates. For example:
class Point2D
attr_accessor :x, :y
def initialize( x, y ) @x, @y = x, y
end
def self.new_polar( r, theta )
new( r * Math::cos( theta ), r * Math::sin( theta ) )
end
end
What you've proposed is a fine idea, but I think that it's important to
be clear about your terminology. Ruby doesn't currently have keyword
arguments. In the example that you've provided you are passing a hash
with symbols for keys into the initialize method and _not_ using
keywords.
Oop, you're of course correct. It's more "I can't believe it's not
keyword arguments", now with 30% less calories than regular argument
passing (yum, syntactic sugar!).