Methods and default values


#1

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


#2

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 :slight_smile:


#3

Michael F. wrote:

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

By the way, I assume that the default “no” should be omitted here,
simply
using @bold as a boolean value.

Malte


#4

2006/2/12, removed_email_address@domain.invalid removed_email_address@domain.invalid:

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