Amatya
Amatya

Reputation: 13

How to omit last character from the each word in ruby?

So I have this paragraph.

Hello how are you doing? how are wew

And I would like to omit all the last "w" character from this paragraph? How do I do this with ruby. I have tried

puts(#{string}).chomp("w")

And I tried the .delete method too.. but it simply deleted all the "w" character from all the word which I don't want it to do.

Thanks in advance.

Upvotes: 0

Views: 100

Answers (2)

Johnson
Johnson

Reputation: 1749

word.split(' ').map(&:chop)

Upvotes: 0

7stud
7stud

Reputation: 48649

i want to get rid or delete last "w" from "wew" but not first "w".But at the same time I also want to delete "w" character from "how" too.

str = "Hello how are you doing? how are wew"
str.gsub!(/w\b/, "")
puts str

--output:--
Hello ho are you doing? ho are we

\b in a regex means "word boundary", which just means look for a non "word character". Word characters are [A-Za-z0-9_]. So the regex w\b looks for a 'w' followed by something that is not [A-Za-z0-9_]. The tricky thing about \b is that it can also match the sliver of nothingness at the beginning or end of a string:

"abcw"
     ^
     |

That string contains a 'w' followed by a word boundary. And this string:

"wabc"
^
|

...starts with a word boundary, and then a 'w'.

Finally, \b doesn't actually match anything--it just ensures that there is a word boundary present, so the regex w\b will only ever match just 'w'.

Upvotes: 2

Related Questions