简体   繁体   English

仅使用 to_s 元素在 Ruby on Rails 中过滤数组

[英]Filter Array in Ruby on Rails with only to_s elements

I have this code that works well我有这个运行良好的代码

def self.select_some_elements(some_value)
   return elements.select { |element| element.some_value > some_value}
end

This code returns an array of elements class instances/objects.此代码返回元素类实例/对象的数组。 However, I would like to return the array of element.to_s instances/propeties, not the whole class objects, just strings/string properties但是,我想返回 element.to_s 实例/属性的数组,而不是整个类对象,只是字符串/字符串属性

Is there a quick way to do it without going extra steps?有没有一种无需额外步骤的快速方法?

Introduction:介绍:

So, what you have achieved is a set (array in this case) of objects, which is great.因此,您所实现的是一组对象(在本例中为数组),这很棒。 What you have to do now is to transform this set into a different one: namely, replace each object with what that object's method to_s returns.您现在要做的是将这个集合转换为不同的集合:即,将每个对象替换为该对象的方法to_s返回的内容。 There's a perfect method for that, called map .有一个完美的方法,称为map It goes through all the items, calls a block with each item as an argument and puts in the resulting array what the block has returned:它遍历所有项目,以每个项目作为参数调用一个块,并将该块返回的内容放入结果数组中:

Open irb console and play around:打开irb控制台并播放:

>> [1,2,3].map{|x| 1}
=> [1, 1, 1]
>> [1,2,3].map{|x| x+1}
=> [2, 3, 4]
>> [1,2,3].map{|x| "a"}
=> ["a", "a", "a"]
>> [1,2,3].map{|x| x.to_s}
=> ["1", "2", "3"]
>> [1,2,3].map(&:to_s)
=> ["1", "2", "3"]

The last transformation seems to be what you need:最后的转换似乎是您所需要的:

The answer: Add .map(&:to_s) at the end like this答案:像这样在最后添加.map(&:to_s)

def self.select_some_elements(some_value)
   return elements.select { |element| element.some_value > some_value}.map(&:to_s)
end

.map(&:to_s) is a short version of .map { |element| element.to_s } .map(&:to_s).map { |element| element.to_s }的简短版本.map { |element| element.to_s } . .map { |element| element.to_s } . And you can read about Arra3#map in the docs你可以在文档中阅读Arra3#map

And when you wrap your head around the #map , check out Stefan's answer which shows how select{}.map can be "compressed" into one filter_map call (doing both things: filter, and mapping in one iteration over the set instead of two).当你把头放在#map ,请查看Stefan 的答案,其中显示了如何将select{}.map压缩到一个filter_map调用中(做两件事:过滤器,并在一次迭代中映射而不是两次)。

Starting with Ruby 2.7 there's filter_map :从 Ruby 2.7 开始,有filter_map

elements = [1, 2, 3, 4, 5]

elements.filter_map { |e| e.to_s if e > 2 }
#=> ["3", "4", "5"]

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

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