HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Creating work notes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creatingworknotes

Problem

I've created a program that will create work notes for me, however, I've been under the impression since I started writing in Ruby that while loops are bad. How can I write this differently in order to gain the same effect or an even better effect?

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


Is there a better way for me to write this without using while loops that will be more Ruby-ish?

Solution

Naming is an important part of the code.

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


Your argument is more than a simple input, it's a message to display in the prompt. You could rename it something message_to_prompt or something similar.

I am not a fan of comparing boolean to have a negation. The negation operator exist for a good reason! Use : while input.empty? ! What would have been better is either a not_empty? or blank? method! This express exactly what you want to do!

I know this is a script for your personnal use, but keep in mind that beginning the program with a small how-to is somewhat profitable!

Regarding your while loop, sometimes even if does not feel like the most ruby way there are still good case to use it, and your case is one. Since you're depending on user input to terminate you don't really know when you're going to finish looping.

Code Snippets

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

Context

StackExchange Code Review Q#138796, answer score: 2

Revisions (0)

No revisions yet.