Object evaluation


#1

Hey,

Whenever I want to DRY some code, I want to do the following:

irb(main):001:0> @my_first_var = ‘RoR rocks!’
=> “RoR rocks!”
irb(main):002:0> [‘first’].each do |attr|
irb(main):003:1* puts @my_"#{attr}"_var
irb(main):004:1> end

Surprisingly, this perfectly works:

array.each do |sym|
  define_method("#{sym}=") do

…/…
end
end

Any idea for the first snippet to work?

Thanks in advance.


,========================.
| Pierre-Alexandre M. |
| email : removed_email_address@domain.invalid |
`========================’


#2

Hi –

On 3/6/07, Pierre-Alexandre M. removed_email_address@domain.invalid wrote:

Hey,

Whenever I want to DRY some code, I want to do the following:

irb(main):001:0> @my_first_var = ‘RoR rocks!’
=> “RoR rocks!”
irb(main):002:0> [‘first’].each do |attr|
irb(main):003:1* puts @my_"#{attr}"_var
irb(main):004:1> end

Try this:

puts instance_variable_get("@my_#{attr}_var")

Surprisingly, this perfectly works:

array.each do |sym|
  define_method("#{sym}=") do
    ../..
    end
end

What’s surprising about it? :slight_smile:

David


Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)


#3

For the posterity:

irb(main):001:0> attr = ‘first’
=> “first”
irb(main):002:0> instance_variable_set("@my_#{attr}var",‘Ror rocks!’)
=> “Ror rocks!”
irb(main):003:0> instance_variable_get("@my
#{attr}var")
=> “Ror rocks!”
irb(main):004:0> instance_variable_set("@my
#{attr}var",‘Django
doesn’t!’)
=> “Django doesn’t!”
irb(main):005:0> instance_variable_get("@my
#{attr}_var")
=> “Django doesn’t!”


,========================.
| Pierre-Alexandre M. |
| email : removed_email_address@domain.invalid |
`========================’


#4

HI –

On 3/6/07, Pierre-Alexandre M. removed_email_address@domain.invalid wrote:

That the first piece of code doesn’t work and the second does. There is
no big difference between them, is it?

In the first one you did something like:

puts @"#{attr}"

rather than putting it all in a string.

David


Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)


#5

On Tue, Mar 06, 2007 at 05:26:04PM -0500, David A. Black wrote :

Try this:

puts instance_variable_get("@my_#{attr}_var")

Dude, that’s pretty cool. Thanks.

What’s surprising about it? :slight_smile:

That the first piece of code doesn’t work and the second does. There is
no big difference between them, is it?


,========================.
| Pierre-Alexandre M. |
| email : removed_email_address@domain.invalid |
`========================’