w3resource

Ruby Basic Exercises: Create a string using the first two characters

Ruby Basic: Exercise-35 with Solution

Write a Ruby program to create a string using the first two characters (if present) of a given string if the first character is 'p' and second one is 's' otherwise return a blank string.

Ruby Basic Exercises:  Create a string using the first two characters

Ruby Code:

def text_test(str)
   len = str.length();
   temp = "";
	if(len >= 1)
	   if(str.slice(0) == 'p')
			temp += str.slice(0);
		if(len >= 2)
			if(str.slice(1) == 's')
			temp += str.slice(1);
		    end	
	    end
	  end
	end 
  return temp;
end
print text_test("psabcd"),"\n"
print text_test("abcd")

Output:

ps

Flowchart:

Flowchart: Create a string using the first two characters

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check whether a string 'Java' appears at index 1 in a given sting, if 'Java' appears return the string without 'Java' otherwise return the string unchanged.
Next: Write a Ruby program to check two integers and return whichever value is nearest to the value 10, or return 0 if two integers are equal.

What is the difficulty level of this exercise?