Ruby练习-块到数组
我在玩Ruby游戏,但我被困在了这一点上: 以低于API的方式实现类Ruby练习-块到数组,ruby,Ruby,我在玩Ruby游戏,但我被困在了这一点上: 以低于API的方式实现类Squirrel squirrel = Squirrel.new squirrel.fight do jump kick punch jump end squirrel.actions #=> ['jump', 'kick', 'punch', 'jump'] 我正在试验def find(&block)并在以后将其保存为Proc,但可能不应该这样做。如果有任何提示,我将不胜感激 如果有任何提示,我将不胜
Squirrel
squirrel = Squirrel.new
squirrel.fight do
jump
kick
punch
jump
end
squirrel.actions #=> ['jump', 'kick', 'punch', 'jump']
我正在试验def find(&block)
并在以后将其保存为Proc,但可能不应该这样做。如果有任何提示,我将不胜感激
如果有任何提示,我将不胜感激
当然<代码>战斗应接受一个块并实例评估
它jump
、kick
和其他方法应该是同一类上的方法
如果有任何提示,我将不胜感激
当然<代码>战斗应接受一个块并
实例评估
它jump
、kick
和其他方法应该是同一类上的方法。尝试instance\u eval
。和/或阅读以下内容:
尝试
实例评估
。和/或阅读以下内容:
这是一种相当标准的元编程技术,多年前由的Gem中的和类推广 其主要思想是创建一个“blankslate”对象,即没有方法的对象,然后记录对该对象的所有方法调用 以下是一种可能的实现:
class Squirrel
class Recorder < BasicObject
(instance_methods + private_instance_methods).each(&method(:undef_method))
def method_missing(method) @actions << method.to_s end
end
attr_reader :actions, :recorder
private
attr_writer :actions, :recorder
def initialize
self.actions = []
self.recorder = Recorder.allocate
Object.public_instance_method(:instance_variable_set).bind(recorder).(:@actions, actions)
end
public def fight(&block)
BasicObject.public_instance_method(:instance_eval).bind(recorder).(&block)
end
end
require 'minitest/autorun'
describe Squirrel do
before do @squirrel = Squirrel.new end
describe '#fight' do
it 'should record its actions' do
@squirrel.fight do jump; kick; punch; jump end
@squirrel.actions.must_equal %w[jump kick punch jump]
end
end
end
类松鼠
类记录器<基本对象
(实例\方法+私有\实例\方法)。每个(&方法(:undef \方法))
def method_missing(method)@actions这是一种相当标准的元编程技术,多年前由的Gem中的和类推广
其主要思想是创建一个“blankslate”对象,即没有方法的对象,然后记录对该对象的所有方法调用
以下是一种可能的实现:
class Squirrel
class Recorder < BasicObject
(instance_methods + private_instance_methods).each(&method(:undef_method))
def method_missing(method) @actions << method.to_s end
end
attr_reader :actions, :recorder
private
attr_writer :actions, :recorder
def initialize
self.actions = []
self.recorder = Recorder.allocate
Object.public_instance_method(:instance_variable_set).bind(recorder).(:@actions, actions)
end
public def fight(&block)
BasicObject.public_instance_method(:instance_eval).bind(recorder).(&block)
end
end
require 'minitest/autorun'
describe Squirrel do
before do @squirrel = Squirrel.new end
describe '#fight' do
it 'should record its actions' do
@squirrel.fight do jump; kick; punch; jump end
@squirrel.actions.must_equal %w[jump kick punch jump]
end
end
end
类松鼠
类记录器<基本对象
(实例\方法+私有\实例\方法)。每个(&方法(:undef \方法))
def method_missing(method)@actions这个练习没有包含一个名为find
的方法,你为什么要定义它?@Stefan:我想他的意思是fight
这个练习没有包含一个名为find
的方法,你为什么要定义它?@Stefan:我想他是说fight
他没有要求一个完整的解决方案。只是暗示。你把所有的乐趣都带走了:)他没有要求一个完整的解决方案。只是暗示。你把所有的乐趣都带走了:)