w3resource

Ruby String Exercises: Remove last specified characters from a given string

Ruby String: Exercise-6 with Solution

Write a Ruby program to remove last specified characters from a given string.

Ruby String Exercises: Remove last specified characters from a given string

Ruby Code:

def check_string(n, my_string)
  n.times do my_string.chop! end
  return my_string
end
print check_string(1, "JavaScript")
print "\n",check_string(2, "JavaScript")
print "\n",check_string(3, "JavaScript")
print "\n",check_string(4, "JavaScript")
print "\n",check_string(5, "JavaScript")

Output:

JavaScrip
JavaScri
JavaScr
JavaSc
JavaS

Flowchart:

Flowchart: Remove last specified characters from a given string

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to remove all white space within a string.
Next: Write a Ruby program to split a delimited string and convert it to an array.

What is the difficulty level of this exercise?