Reputation: 110950
I have the following:
myObject = {
id: user.id,
email: user.email,
}
I need to add values like so:
if current_user && current_user.id == user.id
myObject << {
notification_email: user.notification_email,
notification_email2: user.notification_email2
}
end
The code above raises an error.
What's the right way to optionally append values to the object?
ERROR
undefined method `<<' for # Did you mean? <
Upvotes: 1
Views: 188
Reputation: 168081
Perhaps you want Hash#merge
.
myObject.merge(
notification_email: user.notification_email,
notification_email2: user.notification_email2
)
If you want side effects, use the banged version.
myObject.merge!(
notification_email: user.notification_email,
notification_email2: user.notification_email2
)
Upvotes: 7
Reputation: 10497
myObject
is a hash, so to add new items you can do this:
if current_user && current_user.id == user.id
myObject[:notification_email] = user.notification_email
myObject[:notification_email2] = user.notification_email2
end
Upvotes: 4