To learn Ruby, I’m implementing different data structures starting with nodes and a simple stack. If I matching each def with a corresponding end, there are lots of error about expecting $end (EOF) but getting end. So I could fix it by stacking some ends at the end of the class, but obviously I don’t know why that works.
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
The node class is very simple and shouldn’t cause any problems:
class Node
attr_accessor :next
def initialize(value)
@value = value
end
end
Everything works fine on that Frankenstein Stack, except pushing a node results in NoMethodError: undefined method +@' for nil:NilClass. Not sure if that is related, but I’m mostly concerned with the syntax of method/class declaration and using end
You get an error because ruby does not have
++and--operators.Ruby understand the following constructs
like
Ruby syntax is expression-oriented and method definition is expression in Ruby. Method definition expressions (
def pop()anddef to_s()) are evaluated tonil(in your code you actually define methodpopinsidepushmethod body andto_sinsidepopmethod body). And this is why you getNoMethodError: undefined method +@' for nil:NilClasserror – it evaluates expressionsize + +niland nil does not define unary plus operator. In this expression first+is anFixnumaddition operator (sizeisFixnum), and second+is unary plus operator ofnil(result ofdef pop()expression).Use
+= 1and-= 1instead of++and--. Your code should look like this: