如果我这样做:
class PseudoRelationship
def my_method(args)
args
end
end
a = PseudoRelationship.new
我得到了输出
x
#<PseudoRelationship:0x109c2ebb0>
我希望它表现得像一个枚举器或数组,所以我得到了例如这个输出
x = PseudoRelationship.new [1,2,3]
x
[1,2,3]
钯。这不适用于 Rails。
我想做的是表现得像一个数组。
rails 2.3好像用的东西,比如你可以做
my_model.relationship # returns an array
my_model.relationship.find #is a method
我正在尝试复制该行为。
最佳答案
jholtrop 很接近,你想覆盖 inspect
方法
2.0.0p645>
class PseudoRelationship
def initialize(args)
@args = args
end
def inspect
@args.inspect
end
end
2.0.0p645> PseudoRelationship.new [2, 3, 5]
[2, 3, 5]
--根据 OP 的想要这种行为的原因进行编辑--
虽然上面的类在控制台中显示我们想看到的,但它实际上并没有以将 args
视为 Enumerable 的方式假设对 args 进行任何管理. OP 的灵感来自 Rails 构造,ActiveRecord::Relation
*。要模拟这种行为风格,您必须包含 Enumerable。
class PseudoRelationship
include Enumerable
def initialize(args)
@args = args
end
def each(&block)
@args.each(&block)
end
def inspect
@args.inspect
end
# Add extra functions to operate on @args
# This is obviously a silly example
def foo?
@args.include? :foo
end
def [](key)
@args[key]
end
def last
@args[-1]
end
end
2.0.0p645> PseudoRelationship.new [2, 3, 5]
[2, 3, 5]
2.0.0p645> x = PseudoRelationship.new [2, 3, 5]
[2, 3, 5]
2.0.0p645> x.each
#<Enumerator: [2, 3, 5]:each>
2.0.0p645> x.each_with_index
#<Enumerator: [2, 3, 5]:each_with_index>
2.0.0p645> x.each_with_index { |e, i| puts "#{i} => #{e}" }
0 => 2
1 => 3
2 => 5
[2, 3, 5]
2.0.0p645> x.foo?
false
2.0.0p645> x.first
2
2.0.0p645> x.last
5
2.0.0p645> x[1]
3
2.0.0p645> x[5]
nil
2.0.0p645> x
[2, 3, 5]
* 这个构造没有明确说明,但我是根据上下文假设的
关于Ruby,如何控制调用实例化对象的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33268694/