Amatya
Amatya

Reputation: 13

How to select certain pattern in an array

Here is my array:

a = ['a','b','c', 'C!', 'D!']

I would like to select any upcase letters followed by the ! character and display them. I was trying:

puts a.select! {|i|  i.upcase + "!"}

which gave me null set. Any help would be greatly appreciated.

Upvotes: 0

Views: 70

Answers (3)

Nona
Nona

Reputation: 5462

Here's another way using the Regexp match method in Ruby.

a.select { |letter| /[A-Z]!/.match(letter) }

Also, one note: consider a more meaningful and contextually relevant variable name than "i" in a.select! {|i| i.upcase + "!"}. For example, I chose the name "letter", although there may be a more meaningful name. It's just a good naming practice that a lot of Ruby programmers tend to follow. Same thing applies to the array named a.

Upvotes: 0

sawa
sawa

Reputation: 168081

puts a.grep(/[A-Z]!/)

will do.

Upvotes: 5

Aguardientico
Aguardientico

Reputation: 7779

Try the following:

a.select {|i| i =~ /[A-Z]!/}

Upvotes: 1

Related Questions