Home > other >  Filter Array in Ruby on Rails with only to_s elements
Filter Array in Ruby on Rails with only to_s elements

Time:09-27

Please forgive me if I didn't formulate my question properly in the header (I am new to Ruby on Rails)

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

Is there a quick way to do it without going extra steps?

CodePudding user response:

add .map(&:to_s) at the end like this

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 }. And you can read about Arra3#map in the docs

CodePudding user response:

Starting with Ruby 2.7 there's filter_map:

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

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