0

I'm looking for a quick way to filter an array in Ruby and am wondering whether the language has a counterpart to the filter method native to the JavaScrpt array object.

4
  • 2
    Out of curiousity, if you type "ruby array filter" into A Famous Web Search Engine, do you not get this or this or this or any of several others within the first few results? Commented Apr 28, 2015 at 6:51
  • Just a suggestion, you have to read ruby array documentation Commented Apr 28, 2015 at 6:54
  • 1
    That said, I'm not seeing a good, simple duplicate of that question here on Stack Overflow. Commented Apr 28, 2015 at 7:04
  • Yep. Even a Google search immediately turned up a bunch of stuff I didn't need. Commented Apr 28, 2015 at 7:06

4 Answers 4

7

You can filter an array by

['a', 'b', 'c'].select{|item| item == 'a'} # ["a"]
Sign up to request clarification or add additional context in comments.

Comments

2

Yes, it has - select.

From documentation:

[1, 2, 3, 4, 5].select { |num|  num.even?  }

Comments

2
[1,2,3].select do |i|
  i > 1
end

1 Comment

Refer to alex's answer to see how you mark up code on SO.
0
class Array
  alias_method :select, :filter
end

1 Comment

A little description/explanation won't be bad with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.