Multiple Initialize methods? 
Author Message
 Multiple Initialize methods?

Hi,

I need to create a class either with a param in the construction or nothing:

something = Object.new

or

something = Object.new(val1, val2)

I have created an emtpy initialize() method and one with the two params.  If
I try to create the object with nothing (first version) then I get
"ArgumentError: wrong number of arguments(0 for 2)".

class Something
 def initialize()
 end
 def initialize(xdim, ydim)


 end

I put the empty initialze in when things didnt work, thinking i needed at
least a marker.

Thanks for any help,

Nick.



Mon, 28 Nov 2005 03:36:18 GMT  
 Multiple Initialize methods?

Quote:

> Hi,

> I need to create a class either with a param in the construction or nothing:

> something = Object.new

> or

> something = Object.new(val1, val2)

> I have created an emtpy initialize() method and one with the two params.  If
> I try to create the object with nothing (first version) then I get
> "ArgumentError: wrong number of arguments(0 for 2)".

> class Something
>  def initialize()
>  end
>  def initialize(xdim, ydim)


>  end

> I put the empty initialze in when things didnt work, thinking i needed at
> least a marker.

> Thanks for any help,

ruby does not support method overloading - you may only a single method
signature for a give name.  you can do something like:

~ > cat foo
class Klass
  def initialize(*args)
    args.size == 0 ?
      init0() :
      init1(*args[0..1])
  end
private
  def init0


  end
  def init1 x, y


  end

end

k = Klass.new
p k
k = Klass.new 4, 2
p k

class Klass
  def initialize args = {}


  end
end

k = Klass.new
p k
k = Klass.new :x => 4, :y => 2
p k

~ > ruby foo
42
42
42
42

-a
--
  ====================================
  | Ara Howard
  | NOAA Forecast Systems Laboratory
  | Information and Technology Services
  | Data Systems Group
  | R/FST 325 Broadway
  | Boulder, CO 80305-3328

  | Phone:  303-497-7238
  | Fax:    303-497-7259
  | ~ > ruby -e 'p(%.\x2d\x29..intern)'
  ====================================



Mon, 28 Nov 2005 03:57:35 GMT  
 Multiple Initialize methods?
You can't overload initialize like that in ruby.

Could you do something like

def initialize(*args) which would give you an array or args of size
args.size

or

def.initialize(val1=nil,val2=nil) with obvious results

Andrew

Quote:

> Hi,

> I need to create a class either with a param in the construction or nothing:

> something = Object.new

> or

> something = Object.new(val1, val2)

> I have created an emtpy initialize() method and one with the two params.  If
> I try to create the object with nothing (first version) then I get
> "ArgumentError: wrong number of arguments(0 for 2)".

> class Something
>  def initialize()
>  end
>  def initialize(xdim, ydim)


>  end

> I put the empty initialze in when things didnt work, thinking i needed at
> least a marker.

> Thanks for any help,

> Nick.



Mon, 28 Nov 2005 04:18:02 GMT  
 Multiple Initialize methods?
Set the parameters to some default value that will let you know if they were
passed:

class Whatever
    NOT_GIVEN = -1
    def initialize(xdim = NOT_GIVEN, ydim = NOT_GIVEN)
        if xdim = NOT_GIVEN
            xdim = foo
etc.

w = Whatever.new
w = Whatever.new(23, 44)

Regards,
  JJ


Quote:
> Hi,

> I need to create a class either with a param in the construction or nothing:

> something = Object.new

> or

> something = Object.new(val1, val2)

> I have created an emtpy initialize() method and one with the two params.  If
> I try to create the object with nothing (first version) then I get
> "ArgumentError: wrong number of arguments(0 for 2)".

> class Something
> def initialize()
> end
> def initialize(xdim, ydim)


> end

> I put the empty initialze in when things didnt work, thinking i needed at
> least a marker.

> Thanks for any help,

> Nick.



Mon, 28 Nov 2005 04:21:20 GMT  
 Multiple Initialize methods?

Quote:

> Hi,

> I need to create a class either with a param in the construction
> or nothing:

>   something = Object.new
> or
>   something = Object.new(val1, val2)

> I have created an emtpy initialize() method and one with the two
> params. If I try to create the object with nothing (first version)
> then I get "ArgumentError: wrong number of arguments(0 for 2)".

> class Something
>   def initialize()
>   end
>   def initialize(xdim, ydim)


>   end

> I put the empty initialze in when things didnt work, thinking i
> needed at least a marker.

Ruby isn't C++; there is no overloading in that way. What you want
is perhaps:

class Something
  def initialize(xdim = nil, ydim = nil)


  end
end

You can also use *args.

-austin
--

software designer * pragmatic programmer * 2003.06.11
                                         * 16:32:43



Mon, 28 Nov 2005 04:35:18 GMT  
 Multiple Initialize methods?

Quote:

>> Hi,

>> I need to create a class either with a param in the construction
>> or nothing:

>>   something = Object.new
>> or
>>   something = Object.new(val1, val2)

>> [snip]

It occurs to me that a standard way to do something like this in Ruby
is as follows (taken from set.rb):

The code below gives two methods to create the object:

Set.new [returns empty set]

Set.new([_array_]) [returns a set, each element of which is an element
of the given array (without duplicates)]

Set.new({_hash_}) [returns a set, each element of which is an array
consisting of the given key-value pairs]

Set[_array_] [returns a set, each element of which is an element of the
given array (without duplicates)]

Set.[](_elements_) [returns a set, each element of which is one of the
given elements (without duplicates)]

Code from set.rb:

   # Creates a new set containing the given objects. [Notice the call to
the 'new' method.]
   def self.[](*ary)
     new(ary)
   end

   # Creates a new set containing the elements of the given enumerable
   # object.
   #
   # If a block is given, the elements of enum are preprocessed by the
   # given block.
   def initialize(enum = nil, &block) # :yields: o

     enum.nil? and return

     if block
       enum.each { |o| add(block[o]) }
     else
       merge(enum)
     end
   end



Mon, 28 Nov 2005 04:50:56 GMT  
 Multiple Initialize methods?
On Wed, 11 Jun 2003 19:36:18 +0000 (UTC)

Quote:

> Hi,

> I need to create a class either with a param in the construction or nothing:

> something = Object.new

> or

> something = Object.new(val1, val2)

Do it like this:

class Something
  def initialize(xdim=defaultval, ydim=defaultvalue)
    # do stuff. When xdim or ydim are not given, they will be set to
"defaultvalue"
  end
end

Or, you could gather the args up in an array:

class Something
  def initialize(*args)
    # Do stuff. args is an array with all arguments given to the method
  end
end

Jason Creighton



Mon, 28 Nov 2005 07:42:14 GMT  
 Multiple Initialize methods?
Hi everybody,

Thanks for the replies.  I appreciate Ruby isnt C++, or C# or Delphi, or ...
but typically you can have more than one constructor in those languages -
because typically people have requested the functionality from the language
because they help.  I think I will reluctantly go with the setting default
values for the params.  Its not nice in my view, but it will do.

Thanks to everyone who replied...much appreciated.

Nick.

Quote:
> On Wed, 11 Jun 2003 19:36:18 +0000 (UTC)

> > Hi,

> > I need to create a class either with a param in the construction or
nothing:

> > something = Object.new

> > or

> > something = Object.new(val1, val2)

> Do it like this:

> class Something
>   def initialize(xdim=defaultval, ydim=defaultvalue)
>     # do stuff. When xdim or ydim are not given, they will be set to
> "defaultvalue"
>   end
> end

> Or, you could gather the args up in an array:

> class Something
>   def initialize(*args)
>     # Do stuff. args is an array with all arguments given to the method
>   end
> end

> Jason Creighton



Mon, 28 Nov 2005 13:11:18 GMT  
 Multiple Initialize methods?

Quote:

> Hi everybody,

> Thanks for the replies.  I appreciate Ruby isnt C++, or C# or Delphi, or ...
> but typically you can have more than one constructor in those languages -
> because typically people have requested the functionality from the language
> because they help.  I think I will reluctantly go with the setting default
> values for the params.  Its not nice in my view, but it will do.

I haven't followed this thread, but has anyone suggested construction
methods (sometimes called factory methods?). Make the constructor
private, and use class methods to construct specific objects:

   class Square
      def Square.with_area(area)
        new(Math.sqrt(area))
      end

      def Square.with_diagonal(diag)
          new(diag/Math.sqrt(2))
      end

      def Square.with_side(side)
          new(side)
      end

      private_class_method :new

      def initialize(side)

      end

   end

   s1 = Square.with_area(4)
   s2 = Square.with_diagonal(2.828427)
   s3 = Square.with_side(2)

The joy of this approach is that not everything has to be done in the
constructor: because no one else can call it, the constructor can create
a partially initialized object, leaving it up to your construction
methods to complete the job.

Cheers

Dave



Mon, 28 Nov 2005 13:29:49 GMT  
 Multiple Initialize methods?

Quote:

> [snip]
> I haven't followed this thread, but has anyone suggested construction
> methods (sometimes called factory methods?). Make the constructor
> private, and use class methods to construct specific objects:

> [snip examples]

I thought I had suggested something like this in my earlier message
citing how set.rb defines a second constructor ( '[ ]' ) that
references the initialize method. Your suggested approach, however,
seems better and clearer.

Should approaches like this (and others that come to be accepted as
best practices) be used in all "official" parts of Ruby that are
written in Ruby?



Mon, 28 Nov 2005 13:54:14 GMT  
 Multiple Initialize methods?

Quote:

> I thought I had suggested something like this in my earlier message
> citing how set.rb defines a second constructor ( '[ ]' ) that
> references the initialize method. Your suggested approach, however,
> seems better and clearer.

> Should approaches like this (and others that come to be accepted as
> best practices) be used in all "official" parts of Ruby that are
> written in Ruby?

There's already for instance File.new and File.open.

--
 _           _                            
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
        Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

No, that's wrong too.  Now there's a race condition between the rm and
the mv.  Hmm, I need more coffee.
        -- Guy Maor on Debian Bug#25228



Mon, 28 Nov 2005 14:24:26 GMT  
 Multiple Initialize methods?

Quote:

> Set the parameters to some default value that will let you know if they were
> passed:

> class Whatever
>     NOT_GIVEN = -1
>     def initialize(xdim = NOT_GIVEN, ydim = NOT_GIVEN)
>         if xdim = NOT_GIVEN

   I think you mean  ==

Quote:
>             xdim = foo
> etc.

Regards,

Brian.



Mon, 28 Nov 2005 14:28:23 GMT  
 Multiple Initialize methods?

see http://www.rubygarden.org/ruby?RubyFromCpp

    robert



Quote:
> Hi,

> I need to create a class either with a param in the construction or
nothing:

> something = Object.new

> or

> something = Object.new(val1, val2)

> I have created an emtpy initialize() method and one with the two params.
If
> I try to create the object with nothing (first version) then I get
> "ArgumentError: wrong number of arguments(0 for 2)".

> class Something
>  def initialize()
>  end
>  def initialize(xdim, ydim)


>  end

> I put the empty initialze in when things didnt work, thinking i needed
at
> least a marker.

> Thanks for any help,

> Nick.



Mon, 28 Nov 2005 16:10:25 GMT  
 Multiple Initialize methods?
Nick,

A common idiom in type-less languages like Ruby, Smalltalk and others is
that you see class methods that take the parameters specific to that usage.
They then turn around and call an internal method that does the actual
construction and then return the result. Much like the Factory pattern.
This makes sense as each class really is a factory for instances.  It also
makes sense to name creation methods for what they are doing instead of just
'new' with another parameter! In C++ your constructor does both your
instance creation and initialization.  In Ruby specifically, those tasks are
separate. But even with that, one of the ideas of OOP is to have your
problem use the domain language.  That should include creating new objects
you need.  I need a new Point or a new Point with X or a new Point with X
and Y.  So making the creation methods read that way is not such a bad idea.

So we may have these methods (based on your example below)
Point.zero
Point.withX(var1)
Point.withX_withY(var1, var2)

Each of these in turn is implemented something like so:

def Point.zero
    return self.new()

    #Could also do this as well - chaining variant of the idea
    #return Point.withX(0)
end

def Point.withX(var1)
    return self.new(var1)

    #Could also do this as well - chaining variant of the idea
    #return Point.withX_withY(var1, 0)
end

def Point.withX_withY(var1, var2)
    return self.new(var1, var2)
end

def initialize(var1 = 0, var2 = 0)


end

This has these positive properties:
1) Method names that mean something in the domain language.
2) Gives class method creation methods that are clearly spelled out. Not
just another variant of new with another parameter
3) Allows the class methods to override the default values if for there case
they want it to be different than what initialize specifics and they are not
given a value for an argument
4) If you use the chaining variant it allows you to work from the most
general usage (no args) to the most specific (all args) and have each
creation method do what it needs to do then pass on the task of creation.
And in Ruby, by the time you get to initialize, lots of error checking on
the args could have already been done, etc. So that initializations need to
do that is minimal.

Hope this idea helps....

--
Sam Griffith Jr.

Web site:   http://homepage.mac.com/staypufd/index.html


Quote:

> Hi everybody,

> Thanks for the replies.  I appreciate Ruby isnt C++, or C# or Delphi, or ...
> but typically you can have more than one constructor in those languages -
> because typically people have requested the functionality from the language
> because they help.  I think I will reluctantly go with the setting default
> values for the params.  Its not nice in my view, but it will do.

> Thanks to everyone who replied...much appreciated.

> Nick.


>> On Wed, 11 Jun 2003 19:36:18 +0000 (UTC)

>>> Hi,

>>> I need to create a class either with a param in the construction or
> nothing:

>>> something = Object.new

>>> or

>>> something = Object.new(val1, val2)

>> Do it like this:

>> class Something
>>   def initialize(xdim=defaultval, ydim=defaultvalue)
>>     # do stuff. When xdim or ydim are not given, they will be set to
>> "defaultvalue"
>>   end
>> end

>> Or, you could gather the args up in an array:

>> class Something
>>   def initialize(*args)
>>     # Do stuff. args is an array with all arguments given to the method
>>   end
>> end

>> Jason Creighton



Mon, 05 Dec 2005 16:34:56 GMT  
 Multiple Initialize methods?

Quote:

> Nick,

> A common idiom in type-less languages like Ruby, Smalltalk and others is

They are not type-less there are dynamically typed.
Doing
   a = 1 + "1"
doesn't work in Ruby, but does in Perl, for example.

Quote:
> that you see class methods that take the parameters specific to that usage.
> They then turn around and call an internal method that does the actual
> construction and then return the result. Much like the Factory pattern.
[...]
> And in Ruby, by the time you get to initialize, lots of error checking on
> the args could have already been done, etc. So that initializations need to
> do that is minimal.

This should all go into the Wiki :-)

--
 _           _                            
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
        Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

Q: What's the big deal about rm, I have been deleting stuff for years?  And
   never lost anything.. oops!
A: ...
        -- From the Frequently Unasked Questions



Mon, 05 Dec 2005 16:46:04 GMT  
 
 [ 21 post ]  Go to page: [1] [2]

 Relevant Pages 

1. newbie question: class method initialize

2. initialize method

3. Extend initialize method in String Class

4. Overriding initialize() methods for SWIG-generated wrapper code?

5. Initializing multiple dimensional arrays

6. Whitespace, parentheses, methods, and arrays (was: Multiple file types in open dialog)

7. methods Accepting multiple data types

8. Efficiency in multiple inheritance attribute/method access

9. multiple arity method ov

10. multiple arity method overloading

11. 1st-class method closures (was Re: Multiple return values)

12. multiple blocks or proc arguments to method

 

 
Powered by phpBB® Forum Software