0

我在查看 ActiveModel::Serializable 时注意到了这个方法

def as_json(args={})
  if root = args[:root] || options[:root]
    options[:hash] = hash = {}
    options[:unique_values] = {}

    hash.merge!(root => serialize)
    include_meta hash
    hash
  else
    serialize
  end
end

而且我真的不知道'if root ='是如何工作的......不应该是'if root =='吗?

4

2 回答 2

6

This is valid Ruby. It will assign the value of args[:root] (if it's not nil), otherwise it will assign the value of options[:root]. The if statement will then evaluate the value of the variable root. If root is truthy (not nil or false), the if statement passes, otherwise it will execute the else clause.

Usually one make this more clear by doing:

if (root = args[:root] || options[:root])
于 2013-08-15T22:00:56.340 回答
5
if root = args[:root] || options[:root]

This will assign the value of args[:root] to root if args[:root] is not nil. If it is nil, then it will assign options[:root] to root. If the final result of root is not nil, then the first branch of the if will be taken. If it is nil, then the else branch will be taken.

于 2013-08-15T22:00:47.523 回答