How do I create an array from my array, that with .select create an array with the elements that begin with the letter p?

1

I have the following array:

nombres = ["Violeta", "Andino", "Clemente", "Javiera", "Paula", "Pia", "Ray"]
a = nombres.select{ |ele|}

I would like to know what would be the instruction to create in the variable a a array different that contains only the elements that begin with the letter P .

    
asked by Upset Grade 04.05.2018 в 19:25
source

1 answer

1

You can use the start_with? method together with select :

a = nombres.select { |nombre| nombre.start_with?("P") }
#=> ["Paula", "Pia"]

If you want to ignore if it is uppercase or lowercase, you could convert everything to lowercase (or uppercase) first; for example:

a = nombres.select { |nombre| nombre.dwoncase.start_with?("p") }
#=> ["Paula", "Pia"]

Or you could also use regexp :

a = nombres.select { |nombre| nombre.match?(/^p/i) }
#=> ["Paula", "Pia"]
    
answered by 04.05.2018 / 20:51
source