Yossale
Yossale

Reputation: 14361

Short way to assign several attributes to the same object in Ruby

I'm looking for a short way to do this:

user.first_name = "first"
user.last_name = "last"
user.email = "[email protected]"

Something like this:

with user:
  first_name = "first"
  last_name = "last"
  email = "[email protected]"

is there such a thing?

Upvotes: 0

Views: 127

Answers (3)

suddenenema
suddenenema

Reputation: 351

for non ActiveRecord you can use instance_eval method, eg:

class SomeClass
   def a(*args)
     @a ||= args
   end

   def b(*args)
     @b ||= args
   end
end

2.0.0 (main):0> some_class_instance = SomeClass.new
=> #<SomeClass:0x007f9b62b629c0>
2.0.0 (main):0 > s = "a 'a args'
2.0.0 (main):0 * b 'b args'"
=> "a 'a args'\nb 'b args'"

2.0.0 (main):0 > some_class_instance.instance_eval(s)
=> ["b args"]
2.0.0 (main):0 > some_class_instance.a
=> ["a args"]
2.0.0 (main):0 > some_class_instance.b
=> ["b args"]

Upvotes: 0

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

What about block? ActiveRecord have many ways for this:

User.new.tap do |user|
  user.name     = "John Doe"
  user.username = "john.doe"
  user.password = "john123"
end

or:

User.new do |user|
  user.name     = "John Doe"
  user.username = "john.doe"
  user.password = "john123"
end

or mix initialize:

User.new(name: "John Doe") do |user|
  user.username = "john.doe"
  user.password = "john123"
end

or super simple with update():

user.update(
  first_name: "first"
  last_name: "last"
  email: "[email protected]"
)

Upvotes: 2

BroiSatse
BroiSatse

Reputation: 44715

If this is ActiveRecord object then:

user.assign_attributes(
  first_name: "first"
  last_name: "last"
  email: "[email protected]"
)

Upvotes: 2

Related Questions