我们将做一些关于函式和变量的练习,以确认你真正掌握了这些知识。这节练习对你来说可以说是一本道:写程序,逐行研究,弄懂它。
不过这节练习还是有些不同,你不需要执行它,取而代之,你需要将它导入到 Ruby 通过自己执行函式的方式运行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
module Ex25 def self.break_words<span class="o">(</span>stuff<span class="o">)</span> <span class="c"># This function will break up words for us.</span> <span class="nv">words</span> <span class="o">=</span> stuff.split<span class="o">(</span><span class="s1">' '</span><span class="o">)</span> words end def self.sort_words<span class="o">(</span>words<span class="o">)</span> <span class="c"># Sorts the words.</span> words.sort<span class="o">()</span> end def self.print_first_word<span class="o">(</span>words<span class="o">)</span> <span class="c"># Prints the first word and shifts the others down by one.</span> <span class="nv">word</span> <span class="o">=</span> words.shift<span class="o">()</span> puts word end def self.print_last_word<span class="o">(</span>words<span class="o">)</span> <span class="c"># Prints the last word after popping it off the end.</span> <span class="nv">word</span> <span class="o">=</span> words.pop<span class="o">()</span> puts word end def self.sort_sentence<span class="o">(</span>sentence<span class="o">)</span> <span class="c"># Takes in a full sentence and returns the sorted words.</span> <span class="nv">words</span> <span class="o">=</span> break_words<span class="o">(</span>sentence<span class="o">)</span> sort_words<span class="o">(</span>words<span class="o">)</span> end def self.print_first_and_last<span class="o">(</span>sentence<span class="o">)</span> <span class="c"># Prints the first and last words of the sentence.</span> <span class="nv">words</span> <span class="o">=</span> break_words<span class="o">(</span>sentence<span class="o">)</span> print_first_word<span class="o">(</span>words<span class="o">)</span> print_last_word<span class="o">(</span>words<span class="o">)</span> end def self.print_first_and_last_sorted<span class="o">(</span>sentence<span class="o">)</span> <span class="c"># Sorts the words then prints the first and last one.</span> <span class="nv">words</span> <span class="o">=</span> sort_sentence<span class="o">(</span>sentence<span class="o">)</span> print_first_word<span class="o">(</span>words<span class="o">)</span> print_last_word<span class="o">(</span>words<span class="o">)</span> end end |
