0

I have a user object which i access like this.. user.email, user.first_name

Now I want to loop through each and return a message based on the current key in loop somewhat like this.

[user.first_name, user.email, user.last_name].each do |key|
      puts "#{key} is required"
 end

The above works but loops through values instead of fields. so will do this below but how to prepend user to keys and get values inside array?

[first_name, email, last_name].each do |key|
 #inside here I want to prepend the user to the keys so that I can access like user.key 

 puts "#{user.key} is required" 
end

If this was a string we can concatenate but how to deal with this here as its a method call?

Abhilash
  • 2,864
  • 3
  • 33
  • 67

3 Answers3

2

With ActiveRecord you can access properties via the [] method:

[ :first_name, :email, :last_name ].each do |key|
  unless (user[key])
    puts "#{key} is required"
  end
end

This generally a lot safer than the send approach because it's not calling arbitrary methods.

tadman
  • 208,517
  • 23
  • 234
  • 262
1

You can simply do:

user.send(key)
jvillian
  • 19,953
  • 5
  • 31
  • 44
-1
[first_name, email, last_name].each do |key|
 puts user.send(key)
end
Ruslan
  • 1,919
  • 21
  • 42