Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Ruby program. Input: sentence Modify: words Output: modified sentence

Tags:

string

ruby

I am new to Ruby. This is a programming interview question to use any language. I am trying to do it in Ruby.

Write a program to input a given sentence. Replace each word with the firstletter/#ofcharactersbetween1st&lastletter/lastletter of the word. All non-alpha (numbers, punctuation, etc.) should not be changed.

Example input: There are 12 chickens for 2 roosters.

Desired output: T3e a1e 12 c6s f1r 2 r6s.

I have the concept but need help with better approach and how to put the parts together:

   s="There are 12 chickens for 2 roosters." 
.. 
=> "There are 12 chickens for 2 roosters."
   a = s.split(" ")
=> ["There", "are", "12", "chickens", "for", "2", "roosters."]
   puts a.length
7
=> nil
   puts a[0].length
5
=> nil
   puts a[0].length-2
3
=> nil
   puts a[0][0]
84
=> nil
   puts a[0][0].chr
T
=> nil
   puts a[0].length-2
3
=> nil
   puts a[0][-1].chr
e
=> nil
like image 617
user2298915 Avatar asked Jan 24 '26 04:01

user2298915


1 Answers

Try this:

s = "There are 12 chickens for 2 roosters."
s.gsub(/([A-Za-z]+)/) { $1[0] + ($1.size - 2).to_s + $1[-1] }

It uses gsub which replaces all parts of the string matching the regular expression pattern.

The pattern in this case is /([A-Za-z]+)/ and groups occurrences of one or more characters in the ranges A-Z and a-z.

{ $1[0] + ($1.size - 2).to_s + $1[-1] } is a block executed for every occurrence. $1 is the first group matched in the pattern. The block replaces the occurrence with its first character $1[0], its length -2 to string ($1.size - 2).to_s and its last character $1[-1].

like image 72
Beat Richartz Avatar answered Jan 26 '26 21:01

Beat Richartz