2016-08-16 65 views
0

我有一个计划,将创建工作笔记对我来说,它的工作原理,但有一个尾随破折号,我想摆脱:如何摆脱尾随破折号

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 

在运行时:

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

我该如何重构这个以消除关卡末端的尾部短划线?

回答

3

我建议你写下如下。

代码

require 'time' 

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

def work_performed 
    1.step.each_with_object([]) do |count, notes| 
    loop do 
     input = prompt "Enter work notes[#{count}]" 
     return notes.join("\n") if input.empty? 
     notes << input 
     loop do 
     input = prompt("Enter work notes[*]") 
     break if input.empty? 
     notes << " - #{input}" 
     end 
    end 
    end 
end 

我们来试试用下面的提示,输入:

[11:38:35] Enter work notes[1]: Pets 
[11:38:39] Enter work notes[*]: dog 
[11:38:40] Enter work notes[*]: cat 
[11:38:41] Enter work notes[*]: pig 
[11:38:42] Enter work notes[*]: 
[11:38:43] Enter work notes[1]: Friends 
[11:38:53] Enter work notes[*]: Lucy 
[11:38:55] Enter work notes[*]: Billy-Bo 
[11:39:04] Enter work notes[*]: 
[11:39:06] Enter work notes[1]: Colours 
[11:39:15] Enter work notes[*]: red 
[11:39:18] Enter work notes[*]: blue 
[11:39:20] Enter work notes[*]: 
[11:39:22] Enter work notes[1]: 

我们得到:

puts work_performed 
Pets 
    - dog 
    - cat 
    - pig 
Friends 
    - Lucy 
    - Billy-Bo 
Colours 
    - red 
    - blue 

注意

  • 我做了notes的阵列,而不是一个字符串,因此需要notes.join("\n")
  • 1.step返回一个枚举数,用于生成以1开头的自然数(请参阅Numeric#step)。
  • loop do(见Kernel#loop)比while true更习惯用法。
+0

这是美丽的。 –

+1

我很乐意提供帮助。 –

5

<< " - #{input}\n"将始终追加一些内容,即使input是空字符串,因此您可以检查它是否为空以有条件追加。

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

几乎但不完全。由于'input'是一个字符串,它将是'empty?',但从来没有'nil?'。 – tadman

+0

@tadman:很好。我已经修改了我的答案。 – Makoto

+0

@Makoto好吧,这是一个很容易,然后我的预期。谢谢! –