繁体   English   中英

在Ruby中使用条件逻辑进行数组哈希处理吗?

[英]Array to Hash with conditional logic in Ruby?

ruby 2.1.1

有没有一种方法可以一行代码或更简洁地完成这段代码中的逻辑?

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

如果您使用的是Rails,并且User是ActiveRecord模型(使用has_attribute?看起来很像has_attribute? ),那么它将执行相同的操作:

user = User.new
...
return user.attributes.slice("name", "foo", "bar")

或者,如果您真的想要符号:

return user.attributes.with_indifferent_access.slice(:name, :foo, :bar)

看来您正在使用Rails。 如果是这样,那么-

attrs = [:name, :foo, :bar]
# the result hash will be returned, if last line of the method.
user.attributes.extract!(*attrs) 

看看这些方法extract! attributes

范例:

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 >

上面的答案在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

我已经将它们格式化为非一线形式,但是它们仍然是单陈述式:)

基本上,诀窍是“发明正确的方法链以将一个序列转换为另一序列”,并且需要了解所有可枚举的序列转换方法(map / select / reduce / reject / ...)以及一种转换方法键值对数组的哈希值(在#to_h 2.1.1中, #to_h是标准)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM