Chop last character of string

224 Views Asked by At

I want to make program which takes the string and chop last character each time and print result to console:

With an input string of Hello, the result should be:

Hello
Hell
Hel
He
H

This is my code so far:

def test_string
  puts "Put your string in: "
  string = gets.chomp


  while string.length == 0
    puts string.chop(/.$/)
  end


 end

 puts test_string
3

There are 3 best solutions below

0
Jagdeep Singh On

Use chop!:

string = gets.chomp

# Print full string, e.g. "Hello"
puts string

# Print remaining... e.g. "Hell", "Hel", etc.
while string.length != 0
  puts string.chop!
end
1
msfk On

Following code does not modify the original string

string = gets.chomp
l = string.length
l.times do |i|
  puts string[0..(l-i-1)]
end
1
Sebastián Palma On

You can also create an array filling it with the string N times, and for each time, get a character less from it:

str = 'Hello'
Array.new(str.size) { |index| str[0...str.size - index] }.each { |str| p str }
# "Hello"
# "Hell"
# "Hel"
# "He"
# "H