I'm writing a compiler in Ruby, and I have many classes where instance methods will modify instance variables. For example, my lexer (the part that finds tokens in the code), works like this:
class Lexer
attr_accessor :tokens
def initialize(input)
@input = input
@tokens = nil
end
def lex!
# lex through the input...
# @tokens << { lexeme: 'if', kind: :if_statement }
@tokens
end
end
lexer = Lexer.new('if this then that')
lexer.lex! # => [ { lexeme: 'if', kind: :if_statement }, ... ]
lexer.tokens # => [ { lexeme: 'if', kind: :if_statement }, ... ]
Is this a valid practice? Or, should I use an approach where the methods (like #lex) take in the input and return the results, without modifying the instance variables?
class Lexer
def initialize
end
def lex(input)
# lex through the input...
# tokens << { lexeme: 'if', kind: :if_statement }
tokens
end
end
lexer = Lexer.new
lexer.lex('if this then that') # => [ { lexeme: 'if', kind: :if_statement }, ... ]