Davide
Davide

Reputation: 17

Move all consonants in a string until the first vowel is met

I'm trying to move all consonants in order at the end of a string as soon as the first vowel is encountered.

For example, with this code the goal I would like to achieve is to have the word "atch"

sentence = 'chat'
splitted = sentence.chars
splitted.each do |letter|
  %w[a e i o u].include?(letter) ? break : splitted << splitted.shift
end

p splitted.join

But what I finally get is "hatc" Any suggestions on how to implement this?

Upvotes: 0

Views: 229

Answers (1)

eux
eux

Reputation: 3282

You could try:

vowels = %w[a e i o u]
sentence = 'chat'
splitted = sentence.chars
right_part = []

sentence.each_char do |letter|
  vowels.include?(letter) ? break : right_part << splitted.shift
end

new_sentence = (splitted + right_part).join

p new_sentence # => "atch"

Upvotes: 1

Related Questions