Forum: Ruby Defining an object constructor that look like [] or {} ...?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9ea8229b9b6503cde77171ffcfe2eedc?d=identicon&s=25 Sonny Chee (soroe)
on 2009-01-16 20:16
Hey Guys,

Ruby has built in object constuctors for Array and Hash via [] and {}..
ie:

an_array = [1, 2, 3, 6]
a_hash = {1=>3, 2=>5, 'a'=>'green'}

I would like to do the same for one of my classes.. i.e.

my_object = |2, 3, 5, 7|

should yield the same result as if I had done the following:

my_object = MyClass.new([2, 3, 5, 7])

Is this possible?

Sonny.
9b905791cbdbb1af35b65e02c3217e23?d=identicon&s=25 Tom Link (Guest)
on 2009-01-16 20:27
(Received via mailing list)
> my_object = MyClass.new([2, 3, 5, 7])

You should be able to use

[] as class method:

    my_object = MyClass[2, 3, 5, 7]

a method in Kernel or similar:

    my_object = MyClass(2, 3, 5, 7)

tom.
A61ecce13ed142622f24a5ca3a123922?d=identicon&s=25 Matthew Moss (Guest)
on 2009-01-16 20:52
(Received via mailing list)
On Jan 16, 2009, at 1:15 PM, Sonny Chee wrote:

>
> my_object = |2, 3, 5, 7|
>
> should yield the same result as if I had done the following:
>
> my_object = MyClass.new([2, 3, 5, 7])
>
> Is this possible?
>

Offhand, I doubt you can use || for this task, but you can use [].

     class MyClass
       def MyClass.[](*arr)
         MyClass.new(arr)
       end

       def initialize(arr)
         @arr = arr
       end
     end

     > x = MyClass[2, 3, 5, 7]
     => #<MyClass:0x7a3b4 @arr=[2, 3, 5, 7]>
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-01-17 11:05
(Received via mailing list)
On 16.01.2009 20:15, Sonny Chee wrote:
> should yield the same result as if I had done the following:
>
> my_object = MyClass.new([2, 3, 5, 7])
>
> Is this possible?

No, because you would have to change Ruby's syntax.  See the other
postings for alternatives.

Kind regards

  robert
B57c5af36f5c1f33243dd8b2dd9043b1?d=identicon&s=25 F. Senault (Guest)
on 2009-01-17 12:10
(Received via mailing list)
Le 16 janvier 2009 à 20:26, Tom Link a écrit :

>     my_object = MyClass(2, 3, 5, 7)
A method in Array :

class Array
  def to_my_class
    MyClass.new(self)
  end
end

my_object = [2, 3, 5, 7].to_my_class

Fred
This topic is locked and can not be replied to.