请帮我实现课程Repeat
及其方法:
class Repeat
def initialize(n)
#TODO
end
def each
#TODO
end
end
def n_times(n)
#TODO
end
这段代码:
n_times(2) { |count| puts "You called me #{count} times" }
应该返回此结果:
# You called me 1 times
# You called me 2 times
答案 0 :(得分:1)
欢迎使用StackOverflow。看起来你是OOP的新手,并将一个块传递给Ruby中的方法。这个答案简化了您的问题,只关注将块传递给方法。以下是一些正常运行的代码:
def n_times(n, &block)
n.times do |counter|
yield(counter + 1)
end
end
n_times(2) { |count| puts "You called me #{count} times" }