只有当哈希键的值设置为true时,才能将哈希键转换为数组

时间:2022-06-18 23:26:57

I'm trying to find an elegant and compact way to convert hash keys into array that contains only those that have true as value

我试图找到一种优雅而紧凑的方法,将散列键转换成仅包含具有true值的数组

example = {"foo" => true, "bar" => false, "baz" => true}

become

成为

example = ["foo", "baz"]

4 个解决方案

#1


4  

example = example.keys.select {|key| example[key].eql? true}

p example

output

输出

["foo", "baz"]

#2


4  

The shortest would be example.select{|k, v| v}

最短的就是例子。选择{ | k、v | }

to extract the keys simply add .keys

要提取键,只需添加.keys

EDIT: if like Cary suggests there would be other than boolean values you would have to check for v == true or v.eql? true

编辑:如果像Cary建议的那样,除了布尔值之外,您还需要检查v == = true还是v.eql?真正的

#3


1  

My 2 cents:

我的2美分。

example.collect{|k, v| k if v}.compact

output: ["foo", "baz"]

输出:【“foo”、“记者”】

Which can work also picking false:

也可以选择错误:

example.collect{|k, v| k if !v}.compact

output: ["bar"]

输出(“酒吧”):

..or

. .或

#4


0  

There are a lot of different ways to do this. Here's another one:

有很多不同的方法可以做到这一点。这是另一个,

example.reduce([]) { |memo, (k, v)| v ? memo << k : memo }

Or, similarly:

或者,类似的:

example.each_with_object([]) { |(k, v), memo| memo << k if v }

Or you can use my nutty piecewise gem:

或者你也可以用我的坚果碎片:

example.piecewise { |yielder, (k, v)| yielder << k if v }

#1


4  

example = example.keys.select {|key| example[key].eql? true}

p example

output

输出

["foo", "baz"]

#2


4  

The shortest would be example.select{|k, v| v}

最短的就是例子。选择{ | k、v | }

to extract the keys simply add .keys

要提取键,只需添加.keys

EDIT: if like Cary suggests there would be other than boolean values you would have to check for v == true or v.eql? true

编辑:如果像Cary建议的那样,除了布尔值之外,您还需要检查v == = true还是v.eql?真正的

#3


1  

My 2 cents:

我的2美分。

example.collect{|k, v| k if v}.compact

output: ["foo", "baz"]

输出:【“foo”、“记者”】

Which can work also picking false:

也可以选择错误:

example.collect{|k, v| k if !v}.compact

output: ["bar"]

输出(“酒吧”):

..or

. .或

#4


0  

There are a lot of different ways to do this. Here's another one:

有很多不同的方法可以做到这一点。这是另一个,

example.reduce([]) { |memo, (k, v)| v ? memo << k : memo }

Or, similarly:

或者,类似的:

example.each_with_object([]) { |(k, v), memo| memo << k if v }

Or you can use my nutty piecewise gem:

或者你也可以用我的坚果碎片:

example.piecewise { |yielder, (k, v)| yielder << k if v }