YoYoYo I'm Awesome YoYoYo I'm Awesome - 3 months ago 10
Ruby Question

How to get rid of the trailing dash

I have a program that will create work notes for me, it works, however there's a trailing dash that I would like to get rid of:

def prompt(input)
print "[#{Time.now.strftime('%T')}] #{input}: "
STDIN.gets.chomp
end

def work_performed
count = 0
notes = ''
while true
input = prompt("Enter work notes[#{count += 1}]")
notes << "\n" + "#{input}\n"
if input.empty?
return notes
else
while input.empty? != true
input = prompt('Enter work notes[*]')
notes << " - #{input}\n"
end
end
end
end


When run:

test
- tset
-
test
- tset
-
tset
- tset
-


How can I refactor this to get rid of the trailing dash at the ends of the levels?

Answer

<< " - #{input}\n" will always append something, even if input is the empty string, so you can check to see if it's empty to conditionally append.

<< "  - #{input}\n" unless input.empty?