[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Using a block to configure/initialize a class

Emmanuel Oga

9/25/2007 10:09:00 PM

Hi! i need a solution for this, it's pretty simple but i can't get it to
work...

suppose:

class Options

def self.define_an_option
# ...don't-know-how-implementation :(
end

define_an_option :option1, String
define_an_option :option2, Array
end

Then, i want to do something like this:

opt= Options.new
opt.option1 => ""
opt.option2 => []

opt.option1 do |o|
o= "Hello"
end

opt.option2 do |o|
o << 10
end

options.option1 => "Hello"
options.option2 => [10]

Thats all! Seems pretty simple, but i tried with a lot of variants and I
don't get it to work. Any ideas?

Thanks!
--
Posted via http://www.ruby-....

3 Answers

David A. Black

9/25/2007 10:31:00 PM

0

Morton Goldberg

9/25/2007 10:35:00 PM

0

On Sep 25, 2007, at 6:09 PM, Emmanuel Oga wrote:

> Hi! i need a solution for this, it's pretty simple but i can't get
> it to
> work...
>
> suppose:
>
> class Options
>
> def self.define_an_option
> # ...don't-know-how-implementation :(
> end
>
> define_an_option :option1, String
> define_an_option :option2, Array
> end
>
> Then, i want to do something like this:
>
> opt= Options.new
> opt.option1 => ""
> opt.option2 => []
>
> opt.option1 do |o|
> o= "Hello"
> end
>
> opt.option2 do |o|
> o << 10
> end
>
> options.option1 => "Hello"
> options.option2 => [10]
>
> Thats all! Seems pretty simple, but i tried with a lot of variants
> and I
> don't get it to work. Any ideas?

Have you looked at the built-in class Struct? I think it will supply
what you need.

<code>
Options = Struct.new(:option1, :option2)
opt=Options.new("", [])
opt.option1 = "Hello"
opt.option2 << 10 << 42
opt.option1 # => "Hello"
opt.option2 # => [10, 42]
</code>

Regards, Morton

Emmanuel Oga

9/25/2007 11:51:00 PM

0

Hi! thanks for you replies. I'm going to analyze them. For the moment i
wanted to answer the question of the unnatural api. The reason i wan't
to do it that way is because i'm not going to use String or array for
most of the options, but Structs. So i want a way to let the user do
this

Struct.new "Value", :sub1, :sub2, :sub3 << In fact, the user may not
even know about the Struct::Value class.

class Options
...same as before...
define_option :an_option
end

opt= Options.new

opt.an_option do |o|
o.sub1= ...
o.sub2= ...
o.sub3= ...
end

instead of

an_option.sub1= ...
an_option.sub2= ...
an_option.sub3= ...
--
Posted via http://www.ruby-....