简体   繁体   中英

Evaluating iterator inside each do block in controller

I am trying to iterate through my array separated by white space:

diff_attr = []

%w[name hours].each do |a|
  if @old_place.a != new_place[a.to_sym]
    diff_attr << a
  end
end

I want to compare attributes (name and hours) of two different objects. Right now, I'm getting an undefined method 'a' error. Right now, a is being evaluated as a method of @old_place instead of as a variable.

How do I evaluate the iterator inside the block so that I'm comparing:

@old.place.name != new_place[:name]

instead of

@old.place.a != new_place[:a]

Well, you can either do it like you're doing for new_place (assuming both are ActiveRecord objects):

if @old_place[a] != new_place[a]

Or, use Object#send :

if @old_place.send(a) != new_place.send(a)

While another option is to simply not be afraid and use eval in Ruby:

diff_attr = []

%w[name hours].each do |a|
  if eval("@old_place.#{a}") != new_place[a.to_sym]
    diff_attr << a
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM