Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

methods and default values

0 views
Skip to first unread message

jar...@prosodiemail.com

unread,
Feb 12, 2006, 12:12:31 AM2/12/06
to
Hi all, let's say that I have a very nice:

class Text
def initialize(text, bold="no", italic="no", color="black")
@text=text
@bold=bold
@italic=italic
@color=color
end
end

class TextSet
def initialize
@texts=Array.new
end
def add(text)
@texts.push(text)
end
end

Let's say I dont want to have a attr_writer :italic, :bold, :color
for TextSet because I want my code to look like

foo = TextSet.new
foo.add(Text.new("Hello, my name is"))
foo.add(Text.new("Jerome"))

as opposed to

foo = TextSet.new
text1=Text.new(Text.new("Hello, my name is"))
text2=Text.new(Text.new("Jerome"))
foo.add(text1)
foo.add(text2)

Ok, you follow me? Now let's talk about default value for the Text
constructor.

Let's say I want my name (Jerome) in green.

I have to do foo.add(Text.new("Hello, my name is", "no, "no, "green")),
right?

Question: I'd like to get rid of the useless "no", "no".
Is there a way to specify, that I want an instance of the object with
the default parameters except for one?

Thanks for your ideas


Michael Fellinger

unread,
Feb 12, 2006, 12:23:14 AM2/12/06
to
Hey jarnaud,

Using an hash in that case looks like the most obvious option.
class Text
def initialize(text, options)
@text = text
@bold = options[:bold] || "no"
@italic = options[:italic] || "no"
@color = options[:color] || "black"
end
end

you use it like that:

foo.add text, {:color => "green"}

maybe somebody has some more fancy solution - just wait a bit :)

~~~~manveru

Message has been deleted

Robert Klemme

unread,
Feb 12, 2006, 6:47:26 AM2/12/06
to
2006/2/12, jar...@prosodiemail.com <jar...@prosodiemail.com>:

> Hi all, let's say that I have a very nice:
>
> class Text
> def initialize(text, bold="no", italic="no", color="black")
> @text=text
> @bold=bold
> @italic=italic
> @color=color
> end
> end

I'd represent false by nil or false and not "no". That way you can
directly use the boolean value.

Text = Struct.new( :text, :bold, :italic, :color )

def Text(t,a)
x = {:text=>t,:color=>:black}.update(a)
Text.new(*(Text.members.map{|f| x[f.to_sym]}))
end

def Text2(t,a)
x = a.inject(:text=>t,:color=>:black){|h,(k,v)| h[k]=v unless
k==:text || "no" == v;h }
Text.new(*Text.members.map{|f| x[f.to_sym]})
end

irb(main):021:0> Text("foo", :bold=>true)
=> #<struct Text text="foo", bold=true, italic=nil, color=:black>
irb(main):022:0> Text2("foo", :bold=>true, :italic=>"no")
=> #<struct Text text="foo", bold=true, italic=nil, color=:black>

see also
http://www.rubygarden.org/ruby?KeywordArguments

HTH

robert

--
Have a look: http://www.flickr.com/photos/fussel-foto/


0 new messages