Find value in an array

后端 未结 10 1856
生来不讨喜
生来不讨喜 2020-12-23 23:52

In Ruby, how can I find a value in an array?

10条回答
  •  孤城傲影
    2020-12-24 00:23

    I know this question has already been answered, but I came here looking for a way to filter elements in an Array based on some criteria. So here is my solution example: using select, I find all constants in Class that start with "RUBY_"

    Class.constants.select {|c| c.to_s =~ /^RUBY_/ }
    

    UPDATE: In the meantime I have discovered that Array#grep works much better. For the above example,

    Class.constants.grep /^RUBY_/
    

    did the trick.

提交回复
热议问题