gpt4 book ai didi

Ruby Koans 代理项目

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:35 25 4
gpt4 key购买 nike

我正在浏览 Ruby Koans,我在 about_proxy_object_project.rb
中遇到了麻烦这是我的解决方案

class Proxy
attr_reader :messages

def initialize(target_object)
@object = target_object
# ADD MORE CODE HERE
@messages = []
end

def number_of_times_called(method_name)
@messages.count method_name
end

def called?(method_name)
@messages.include? method_name
end

def method_missing(method_name, *args, &block)
if @object.respond_to? method_name
@object.send(method_name, *args)
@messages << method_name
else
super method_name, *args, &block
end
end
end

但是当我输入 rake 时,我得到了这个

The answers you seek...
Expected 10 to equal [:channel=, :power, :channel]

Please meditate on the following code:
/home/Shanicky/koans/about_proxy_object_project.rb:61:in `test_tv_methods_still_perform_their_function'

在我的about_proxy_object_project.rb

def test_tv_methods_still_perform_their_function
tv = Proxy.new(Television.new)

tv.channel = 10
tv.power

assert_equal 10, tv.channel # this is the 61st line
assert tv.on?
end

我很困惑
我哪里做错了?
谢谢大家

这是我的电视

class Television
attr_accessor :channel

def power
if @power == :on
@power = :off
else
@power = :on
end
end

def on?
@power == :on
end
end

最佳答案

在此if子句:

if @object.respond_to? method_name  
@object.send(method_name, *args)
@messages << method_name # <-- this is the return value you get
else
super method_name, *args, &block
end

支票@object.respond_to? method_name总是评估为 true因为Television类定义了您在其对象上调用的所有这些方法( channel=powerchannel )。因此if的第一个分支运行并且此代码实质上添加到 @messages实例变量(这是一个 Array )您正在调用的方法名称。

所以当你调用tv.channel该方法的返回值是上面代码中的注释语句,当然不等于10 .您实际上得到了 @messages << method_name 的返回值这是新的 @messages数组,它实际上包含您在此之前调用的所有未定义方法:[:channel=, :power, :channel] .

关于Ruby Koans 代理项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22192173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com