C
cibercitizen1
I tried to
class Foo
attr_accessor :bar1, :bar2
def initialize( &bloc )
instance_eval( &bloc )
end
end
and then
f = Foo.new {
bar1 = 12345
bar2 = 44444
}
but this doesn't work
unless you write @bar1=12345 in the block, as
Ruby does not consider bar1= a method call but an assignment.
Here's my solution. Any comments?
#--------------------------------
module MyAccessor
def my_attr (nou, defval=nil)
class_eval "
def #{nou} (s=nil)
@#{nou} = s || @#{nou} || '#{defval}'
end
"
end # def my_attr
end # module
#--------------------------------
class Foo
extend MyAccessor
my_attrtitle, "default title")
my_attrheight, 100)
my_attrcolor, 'black')
def initialize( &bloc )
instance_eval( &bloc )
end # def
def show
puts "attributes ----------"
puts "title="+ title.to_s
puts "color="+ color.to_s
puts "height="+ height.to_s
end
end
#----------------------------------
#----------------------------------
fo = Foo.new() {
color "red"
height 50
}
puts "---------------------------"
fo.show
puts "---------------------------"
fo.color("blue")
puts fo.color
puts "---------------------------"
fo.show
class Foo
attr_accessor :bar1, :bar2
def initialize( &bloc )
instance_eval( &bloc )
end
end
and then
f = Foo.new {
bar1 = 12345
bar2 = 44444
}
but this doesn't work
unless you write @bar1=12345 in the block, as
Ruby does not consider bar1= a method call but an assignment.
Here's my solution. Any comments?
#--------------------------------
module MyAccessor
def my_attr (nou, defval=nil)
class_eval "
def #{nou} (s=nil)
@#{nou} = s || @#{nou} || '#{defval}'
end
"
end # def my_attr
end # module
#--------------------------------
class Foo
extend MyAccessor
my_attrtitle, "default title")
my_attrheight, 100)
my_attrcolor, 'black')
def initialize( &bloc )
instance_eval( &bloc )
end # def
def show
puts "attributes ----------"
puts "title="+ title.to_s
puts "color="+ color.to_s
puts "height="+ height.to_s
end
end
#----------------------------------
#----------------------------------
fo = Foo.new() {
color "red"
height 50
}
puts "---------------------------"
fo.show
puts "---------------------------"
fo.color("blue")
puts fo.color
puts "---------------------------"
fo.show