我正在寻找一个短期的方式做到这一点:短的方式在Ruby中
user.first_name = "first"
user.last_name = "last"
user.email = "[email protected]"
事情是这样的:
with user:
first_name = "first"
last_name = "last"
email = "[email protected]"
是有这样的事情?
我正在寻找一个短期的方式做到这一点:短的方式在Ruby中
user.first_name = "first"
user.last_name = "last"
user.email = "[email protected]"
事情是这样的:
with user:
first_name = "first"
last_name = "last"
email = "[email protected]"
是有这样的事情?
如果这是ActiveRecord的对象,然后:
user.assign_attributes(
first_name: "first"
last_name: "last"
email: "[email protected]"
)
什么block
? ActiveRecord
有这么多的方法:
User.new.tap do |user|
user.name = "John Doe"
user.username = "john.doe"
user.password = "john123"
end
或:
User.new do |user|
user.name = "John Doe"
user.username = "john.doe"
user.password = "john123"
end
或混合的initialize:
User.new(name: "John Doe") do |user|
user.username = "john.doe"
user.password = "john123"
end
或超简单与update()
:
user.update(
first_name: "first"
last_name: "last"
email: "[email protected]"
)
非ActiveRec奥德可以使用instance_eval的方法,如:
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"]
'tap'是不是从'ActiveRecord' http://ruby-doc.org/core-2.1.2/Object.html#method-i-tap – IS04 2014-08-28 11:31:42
@ IS04我知道这件事。我不会说'tap'只能在'AR'中使用 – 2014-08-28 11:33:19