synopsa
synopsa

Reputation: 75

Chop last character of string

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

Upvotes: 0

Views: 234

Answers (3)

Sebastián Palma
Sebastián Palma

Reputation: 33470

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

Upvotes: 2

msfk
msfk

Reputation: 137

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

Upvotes: 2

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

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

Upvotes: 4

Related Questions