2016-08-16 78 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好吧,這是一個很容易,然後我的預期。謝謝! –