w3resource

Ruby Basic Exercises: Check whether a string 'Java' appears at index 1 in a given sting

Ruby Basic: Exercise-34 with Solution

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.

Ruby Code:

def text_test(str)
   if(str[1,4] == "Java")
		return (str[5, str.length()]);
	else
		return str;
	end
end
print text_test("ZJavaScript"),"\n"
print text_test("Oldjava")

Output:

Script
Oldjava

Flowchart:

Flowchart: Check whether a string 'Java' appears at index 1 in a given sting

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to test whether a year is leap year or not.
Next: 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.

What is the difficulty level of this exercise?