2012-12-29 54 views
1

好了,所以我試圖solve step 2 in this puzzle,我有麻煩了。我的問題是在試圖訪問一個實例變量(@name)甚至呼籲類(name getter)方法,紅寶石告訴我不確定局部變量。對我來說,這似乎是一個範圍問題。當一個動作名稱和一個塊作爲參數給出時,問題就出現了。單身人士正在成功添加到實例變量,我相信但調用它,紅寶石告訴我,「名稱」是一個未定義的局部變量。有任何想法嗎?任何想法如何更有效地仿效功能的其他方式?添加單方法和訪問實例變量 - 未定義

這裏是我的Dog.rb類:

class Dog 
    MSGS = {:dance => 'is dancing', :poo => 'is a smelly doggy!', :laugh => 'finds this hilarious!'} 
    attr_accessor :name 

    def initialize(name) 
    @name = name 
    end 

    def can(*actions) 
    actions.each do |action| 
     self.instance_eval do 
     if block_given? 
      define_singleton_method action do 
      yield 
      end 
     else 
      define_singleton_method(action) do 
      name + ' ' + MSGS[action] 
      end 
     end 
     end 
    end 
    end 

    def method_missing(method_name,*args) 
    name + " can't " + method_name.to_s 
    end 
end 

這裏是Dog_Game.rb從拼圖:

require './dog' 

lassie, fido, stimpy = %w[Lassie Fido Stimpy].collect{|name| Dog.new(name)} 
lassie.can :dance, :poo, :laugh 
fido.can(:poo){"#{name} is just wayyyy too smelly."} #name here is the source of the problem 
stimpy.can :dance 
stimpy.can(:cry){"#{name} cried AHHHH"} 

p lassie.dance 
p lassie.poo 
p lassie.laugh 
puts 
p fido.dance 
p fido.poo 
p fido.laugh 
puts 
p stimpy.dance 
p stimpy.poo 
p stimpy.laugh 
p stimpy.cry 

回答

1

1: 您創建一個醜陋的方法:

self.instance_eval {} == define_singleton_method(回調,&塊)

你應該我們一個而不是兩個!

2: 因爲當你使用

self.instance_eval do 
    #coding 
end 

你不能使用varible範圍進行了更改:姓名,所以只用define_singleton_method!

對不起,我的英語很差!

+0

謝謝!現在按預期工作 – foklepoint

1

傳遞塊define_singleton_method如果這是你想要的是什麼方法是:

def can(*actions, &block) 
    actions.each do |action| 
    if block_given? 
     define_singleton_method(action, block) 
    else 
     define_singleton_method(action) { "#{name} #{MSGS[action]}" } 
    end 
    end 
end 

這會輸出你的電子郵件xpect。

(三角洲把史丁比首次證明cry是不是在其他情況下,和cry調用每個)

Stimpy is dancing 
Stimpy can't poo 
Stimpy can't laugh 
Stimpy cried AHHHH 

Lassie is dancing 
Lassie is a smelly doggy! 
Lassie finds this hilarious! 
Lassie can't cry 

Fido can't dance 
Fido is just wayyyy too smelly. 
Fido can't laugh 
Fido can't cry 
+0

沒錯。工作謝謝 – foklepoint