当且仅当 Array2 元素与哈希值(不是键)匹配时,用 Array2 字符串元素填充 ruby Array1
我有一个 ruby hash:
VALS = { :one => "One", :two => "Two" }
和一个 Array:
array2 = ["hello", "world", "One"]
问题:如何填充新的 array1,以便它只提取 array2 中与 VALS 中的值完全匹配的任何值?
例如,我尝试过:
array2.each_with_index do |e,i|
array1 << e if VALS[i] ~= e
end
与其他东西一起使用,但没有任何效果。小白。
谢谢
辉煌!但是当我尝试时:
p array.select { |i| hash.has_value? i ? array[i+1] : "foo"}
我收到了无法转换 fixnum 错误。我一定是错过了什么。
I have a ruby hash:
VALS = { :one => "One", :two => "Two" }
and an Array:
array2 = ["hello", "world", "One"]
Question: How can I populate a new array1 so that it only pulls in any values in array2 that match exactly the values in VALS?
For example, I have tried:
array2.each_with_index do |e,i|
array1 << e if VALS[i] ~= e
end
Along with other thing, and none work. Noob.
Thanks
brilliant! but whent I tried:
p array.select { |i| hash.has_value? i ? array[i+1] : "foo"}
I got an can't convert fixnum error. I must be missing something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果两个集合都很大,则使用嵌套循环会非常慢。最好将内容视为集合:
输出:
Using nested loops would be very slow if both collections are large. It's better to treat the contents as sets:
Output:
这是一个选项:
Here's an option:
知道了!
got it!