2014-02-28 21 views
0

我只是不知道为什么我的代码停止,并不明白我的终端想告诉我什么。我的代码工作,直到pop然后我得到:pop在我的Ruby程序中不起作用?

NameError: undefined local variable or method `word' for Ex25:Module 

这是代码:

module Ex25 
    def self.break_words(stuff) 
    # This function will break up words for us. 
    words = stuff.split(' ') 
    words 
    end 

    def self.sort_words(words) 
    # Sorts the words. 
    words.sort() 
    end 

    def self.print_first_word(words) 
    # Prints the first word and shifts the others down 
    word = words.shift() 
    puts word 
    end 

    def self.print_last_word(words) 
    # Print the last word after popping it off the end. 
    words = words.pop() 
    puts word 
    end 

在IRB运行此:

irb(main):004:0> sorted_words = Ex25.sort_words(words) 
=> ["All", "come", "good", "things", "those", "to", "wait.", "who"] 
irb(main):005:0> Ex25.print_first_word(words) 
All 
=> nil 
irb(main):006:0> Ex25.print_last_word(words) 
NameError: undefined local variable or method `word' for Ex25:Module 
from /Users/lemonsquares/Ruby/ex25.rb:22:in `print_last_word' 
from (irb):6 
from /usr/bin/irb:12:in `<main>' 

回答

3
def self.print_last_word(words) 
    # Print the last word after popping it off the end. 
    words = words.pop() 
    puts word 
end 

应该

def self.print_last_word(words) 
    # Print the last word after popping it off the end. 
    word = words.pop() 
    puts word 
end 

你刚刚有一个错字我想 - 看看第三行的差异。

+0

我知道这是件小事。叹息感谢帮助我得到我的海腿! – user3363204

0

实际上,要获得firstlast,您需要使用名为first和“last”的Ruby数组方法。

您的程序可以写成

def self.break_words(stuff) 
    # This function will break up words for us. 
    stuff.split(' ') 
    end 

    def self.sort_words(words) 
    words.sort 
    end 

    def self.print_first_word(words) 
    words.first 
    end 

    def self.print_last_word(words) 
    words.last 
    end 

这是因为在Ruby中,该方法的最后一行将自动返回:),并删除明显的意见。

相关问题