w3resource

Ruby Basic Exercises: Check a given string contains 'i' characters

Ruby Basic: Exercise-39 with Solution

Write a Ruby program to check a given string contains 'i' characters.

Ruby Basic Exercises: Check a given string contains 'i' characters

Ruby Code:

def test_str(str)
    count = 0
    for  i in  0..str.length do
    	if(str.slice(i) == 'i')
       		count = count + 1
		end
	  end
	return (count >= 1 && count <= 3);
end

print test_str('Python'),"\n"
print test_str('Diligent1'),"\n"
print test_str('Industrious'),"\n"
print test_str('Impartiality')

Output:

false
true
true
true

Flowchart:

Flowchart: Check a given string contains 'i' characters

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check two positive integer values and return the larger value that is in the range 20..30 inclusive, or return 0 if no number is in that range.
Next: Write a Ruby program to create a new string taking every other character starting with the first of a given string.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/ruby-exercises/basic/ruby-basic-exercise-39.php