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
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% 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