[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

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

Sonny Chee

1/16/2009 7:15:00 PM

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.
--
Posted via http://www.ruby-....

4 Answers

ThoML

1/16/2009 7:26:00 PM

0

> 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.

Matthew Moss

1/16/2009 7:50:00 PM

0


On Jan 16, 2009, at 1:15 PM, Sonny Chee wrote:

> 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?
>

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]>



Robert Klemme

1/17/2009 10:02:00 AM

0

On 16.01.2009 20:15, Sonny Chee wrote:
> 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?

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

Kind regards

robert


--
remember.guy do |as, often| as.you_can - without end

F. Senault

1/17/2009 11:08:00 AM

0

Le 16 janvier 2009 à 20:26, Tom Link a écrit :

>> 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)

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
--
You believe this heat Another empty house, another dead end street
Gonna rest my bones and sit for a spell
This side of heaven, this close to hell
(Guns n' Roses, Right Next Door to Hell)