From: Intransition on
On May 30, 6:17 pm, Wes Bailey <w...(a)verticalresponse.com> wrote:
> irb(main):074:0> class MyTest
> irb(main):075:1> class_eval %w/a b c/.inject( '' ) { |methods,var| methods + "def hello_#{var}?; puts \"hello_#{var}\"; end\n" }
> irb(main):076:1> end
> => nil
> irb(main):077:0> t = MyTest.new
> => #<MyTest:0x86e98>
> irb(main):078:0> t.hello_a?
> hello_a
> => nil
> irb(main):079:0> t.hello_b?
> hello_b
> => nil
> irb(main):080:0> t.hello_c?
> hello_c
> => nil

Yes, that can be done. However, the point was to get the body of loop
to be the thing that stands-out first rather than the loop. My example
was kind of a joke. I just pushed the code that does the loop off to
the right, and the lambda was just for fun. I could have done the same
with the original

[:a, :b, :c].each{ |x|
define_method("#{x}?") do
instance_variable_get("@#{x}")
end
}


First  |  Prev  | 
Pages: 1 2
Prev: Another complete beginners question
Next: Square Root