我正在尝试创建一个全局布尔方法来检查变量是否属于类型
Pair
(我自己的自定义类)。但是,当我尝试运行它时,出现错误
Project4.rb:83:in `<main>': private method `pair?' called for #<Pair:0x00000212de6861e8 @value1=5, @value2=7> (NoMethodError)
puts a.pair?
^^^^^^
我该怎么办?我的代码如下。
#Pair (class): Takes two values and creates a list from them. Executing the code should return a list without displaying any output.
# Returns: A list of at least two elements.
# Parameters:
# value1 (any class, including pair) - a value to insert into list.
# value2 (any class, including pair) - another value to insert into list.
#
#Declare class `Pair`
class Pair
#Initialize
def initialize(value1, value2)
@value1 = value1
@value2 = value2
end
#Method: car - return the car of the pair.
def car
return @value1
end
#Method: cdr - return the cdr of the pair.
def cdr
return @value2
end
#Method: to_s - Return string representation of the pair.
# def to_s
# "(#{@value1} . #{@value2})"
# end
#Method: list? - returns true if pair is a valid list and false otherwise.
def list?
#If value2 is a pair...
if (@value2.class == Pair)
#...Recursively call the list? method again with the cdr.
cdr.list? #Recursion
else
#If value2 is a null (nil) value, then it is a list.
if (@value2 == nil)
return true
else
return false
end
end
end
#Method: count - If the pair is a list, return the number of items in the top level of the list. Return false otherwise.
#Method: append(other) - If the pair is a list, append should return a new list consisting of `other`` appended to the original list.
#Method: null? - returns true only if the pair is an empty list.
def null?
end
#Implement a null/empty list value.
def self.null
nil
end
end
#Implement a global `pair?` method. MUST NOT TAKE PARAMETERS!
def pair?
if (is_a? Pair)
return true
else
return false
end
end
请尽早回复。
puts
或loop
。但是,您的方法确实需要接收器,因为它基于 is_a?
。
您可能不需要全局方法,而是
Object
的实例方法:
class Object
def pair?
is_a?(Pair)
end
end
您甚至可以通过利用继承来省略显式类型检查。在
pair?
中实现一个 Object
方法,它只返回 false
,这是所有对象的默认值:
class Object
def pair?
false
end
end
然后在您的
Pair
中重写此方法以返回 true
:
class Pair
def pair?
true
end
end
示例:
Object.new.pair? #=> false
"a string".pair? #=> false
Pair.new.pair? #=> true
这正是
nil?
的工作原理,请参阅 Object#nil?
和 NilClass#nil?
的实现。