Ruby/Array/grep

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Get array element by using grep

a = ["a", "b", "c", "d", "e", "f", "g", "h"]
p a.grep /[aeiou]/                 # => ["a", "e"]



grep /[^g]/

a = ["a", "b", "c", "d", "e", "f", "g", "h"]
p a.grep /[^g]/                    # => ["a", "b", "c", "d", "e", "f", "h"]



grep numbers

data = [1, 17, 3.0, 4]
ints = data.grep(Integer)           # => [1, 17, 4]: only integers
small = ints.grep(0..9)             # [1,4]: only in range



Start with "p"

langs = %w[ java perl python ruby ]
langs.grep(/^p/)                    # => [perl, python]: start with "p"
langs.grep(/^p/) {|x| x.capitalize} # => [Perl, Python]: fix caps