[英]Array to Hash with conditional logic in Ruby?
ruby 2.1.1
Is there a way to do the logic in this piece of code in one line or a more concise manner? 有没有一种方法可以一行代码或更简洁地完成这段代码中的逻辑?
user = User.new
h = Hash.new
attrs = [:name, :foo, :bar]
attrs.each do |a|
h[a] = user[a] if user.has_attribute? a
end
return h
If you're using Rails and User is an ActiveRecord model (which it looks like given your use of has_attribute?
) then this will do the same thing: 如果您使用的是Rails,并且User是ActiveRecord模型(使用has_attribute?
看起来很像has_attribute?
),那么它将执行相同的操作:
user = User.new
...
return user.attributes.slice("name", "foo", "bar")
Or, if you really want symbols: 或者,如果您真的想要符号:
return user.attributes.with_indifferent_access.slice(:name, :foo, :bar)
It seems you are on Rails. 看来您正在使用Rails。 If so,then - 如果是这样,那么-
attrs = [:name, :foo, :bar]
# the result hash will be returned, if last line of the method.
user.attributes.extract!(*attrs)
Look these methods extract!
看看这些方法extract!
and attributes
. 和attributes
。
Example : 范例:
arup@linux-wzza:~/Rails/app> rails c
Loading development environment (Rails 4.1.1)
2.0.0-p451 :001 > h = { a: 1, b: 2, c: 3, d: 4 }
=> {:a=>1, :b=>2, :c=>3, :d=>4}
2.0.0-p451 :002 > h.extract!(:a ,:b ,:x)
=> {:a=>1, :b=>2}
2.0.0-p451 :003 >
Answers above are correct in Rails scope, I'l just add generic solution: 上面的答案在Rails范围内是正确的,我只添加通用解决方案:
# assuming user[a] returns nil, if user have no a attribute
[:name, :foo, :bar].
map{|a| [attr, user[a]]}.
reject{|k, v| v.nil?}.
to_h
# assuming user[a] can raise if not user.has_attribute?(a)
[:name, :foo, :bar].
map{|a| [attr, user.has_attribute?(a) && user[a]]}.
reject{|k, v| !v}.
to_h
I've formatted them as NOT one-liners, but they are still one-statements :) 我已经将它们格式化为非一线形式,但是它们仍然是单陈述式:)
Basically, the trick is "invent the right method chain to convert one sequence to other", and requires to know all Enumerable sequence-transforming methods (map/select/reduce/reject/...), as well as a method to transform array of key-value pairs into hash ( #to_h
is standard in Ruby 2.1.1) 基本上,诀窍是“发明正确的方法链以将一个序列转换为另一序列”,并且需要了解所有可枚举的序列转换方法(map / select / reduce / reject / ...)以及一种转换方法键值对数组的哈希值(在#to_h
2.1.1中, #to_h
是标准)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.