define_method with instance assignment to proc

T

T. Onoma

I'm having one of Those mornings!

I'm not sure how to overcome the syntax error this causes:

class Module
def cast_writer(name,cast)
if cast.kind_of?(Proc) or cast.kind_of?(Method)
define_method(name) { |x| instance_eval("@#{name}") = cast.call(x) }
end
end
end

syntax error (SyntaxError)
define_method(name) { |x| instance_eval("@#{name}") = cast.call(x) }
^

The problem I see is that @name has to be provided as a string, while cast
cannot be.

Thanks,
T.
 
T

ts

T> define_method(name) { |x| instance_eval("@#{name}") = cast.call(x) }

svg% cat b.rb
#!/usr/bin/ruby
class Module
def cast_writer(name, cast)
if cast.kind_of?(Proc) or cast.kind_of?(Method)
define_method(name) do |x|
instance_variable_set("@" + name.to_s, cast.call(x))
end
end
end
end

a = Object.new
Object.cast_writer:)b, Proc.new {|x| 2 * x})
a.b(12)
p a
svg%

svg% b.rb
#<Object:0x40099d54 @b=24>
svg%


Guy Decoux
 
T

T. Onoma

svg% cat b.rb
#!/usr/bin/ruby
class Module
def cast_writer(name, cast)
if cast.kind_of?(Proc) or cast.kind_of?(Method)
define_method(name) do |x|
instance_variable_set("@" + name.to_s, cast.call(x))
end
end
end
end


Beautiful, Guy! Thank You!

T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top