在Ruby中匹配结束标记
问题描述:
要学习Ruby,我要实现以节点和简单堆栈开始的不同数据结构。如果我将每个def
与相应的结尾相匹配,那么期待$ end(EOF)会出现很多错误,但会得到end
。所以我可以通过在课程结束时堆叠一些end
来修复它,但显然我不知道为什么这会起作用。在Ruby中匹配结束标记
require "Node"
class Stack
attr_accessor :top
def size
@size
end
def push(node)
if node && node.next
node.next = top
top = node
end
size++
def pop()
if top != nil
top = top.next
end
size--
def to_s
if top != nil
temp = top
while temp != nil
puts temp.value
temp = temp.next
end
else
puts "The stack is empty"
end
end
end
end
end
节点类很简单,应该不会造成任何问题:
class Node
attr_accessor :next
def initialize(value)
@value = value
end
end
一切正常的弗兰肯斯坦堆栈,除了在NoMethodError: undefined method [email protected]' for nil:NilClass
推节点结果。不知道这是否有关,但我主要关注方法/类声明的语法和使用方法end
答
你会得到一个错误,因为ruby没有++
和--
操作符。
红宝石理解以下构造
size++
def pop()
# and
size--
def to_s()
像
size + +def pop()
# and
size - -def to_s()
红宝石语法表达导向和方法定义是红宝石表达。方法定义表达式(def pop()
和def to_s()
)评估为nil
(在您的代码中,您实际上在push
方法体内部定义了方法pop
,在pop
方法体内部定义了to_s
)。这就是为什么你会得到NoMethodError: undefined method [email protected]' for nil:NilClass
错误 - 它评估表达式size + +nil
和nil没有定义一元加运算符。在该表达式中,第一个+
是Fixnum
加法运算符(size
是Fixnum
),并且第二个+
是一元加运算符nil
(结果为def pop()
表达式)。
使用+= 1
和-= 1
而不是++
和--
。你的代码应该是这样的:
class Stack
attr_accessor :top
def size
@size
end
def push(node)
if node && node.next
node.next = top
top = node
end
@size += 1 # @size, not `size` because you have `size` getter and you cannot modify size with getter method
end
def pop()
if top != nil
top = top.next
end
@size -= 1
end
def to_s
if top != nil
temp = top
while temp != nil
puts temp.value
temp = temp.next
end
else
puts "The stack is empty"
end
end
end
答
您的def
s没有匹配end
。另外,Ruby没有++
运算符;您必须改用+= 1
。
根据这个问题,OP有他们所属的'end's,但是它给了他语法错误。这就是为什么他将他们删除(这不是最明智的决定)。 – 2012-02-07 20:34:15
@NiklasB .:当然,这个OP在他的假设中是不正确的。 Ruby解析器按照规范工作,语法错误在其他地方,或者他计算他的def/end对错误。 – 2012-02-07 20:35:07
@Ed S .:是的,句法问题是'++',可能使用'next'作为方法名称(虽然不确定)。 – 2012-02-07 20:41:17