0

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
Holger Just
  • 52,918
  • 14
  • 115
  • 123
synopsa
  • 75
  • 1
  • 8
  • Your premise is wrong: `while string.length == 0` means _"as long as string has zero length"_ so the loop is never executed. You want `while string.length != 0` or `until string.length == 0` or more succinct `until string.empty?` – Stefan Jun 28 '18 at 11:57

3 Answers3

4

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
Jagdeep Singh
  • 4,880
  • 2
  • 17
  • 22
2

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
msfk
  • 137
  • 1
  • 15
  • You can pass a _negative_ index to `[]`, thus avoiding the temporary variable: `string.length.times { |i| puts string[0..-i-1] }`. Or use `downto` for a descending loop: `string.length.downto(1) { |l| puts string[0, l] }` – Stefan Jun 28 '18 at 12:03
2

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
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
  • You can avoid the trailing `each` and put the `p` inside your first block `Array.new(str.size) { |index| p str[0...str.size - index] }`. – Sagar Pandya Jun 28 '18 at 17:43