Class: Ast::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/ast_ast/token.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, value) ⇒ Token

Returns a new instance of Token.



5
6
7
8
# File 'lib/ast_ast/token.rb', line 5

def initialize(type, value)
  @type = type
  @value = value
end

Instance Attribute Details

#typeObject

Returns the value of attribute type.



3
4
5
# File 'lib/ast_ast/token.rb', line 3

def type
  @type
end

#valueObject

Returns the value of attribute value.



3
4
5
# File 'lib/ast_ast/token.rb', line 3

def value
  @value
end

Class Method Details

.valid?(arr) ⇒ Boolean

Check whether an array given is valid, ie. it has a symbol then one or no objects only.

Examples:


Ast::Token.valid? [:type, 'val'] #=> true
Ast::Token.valid? ['wrong', 'val'] #=> false
Ast::Token.valid? ['too', 'long', 1] #=> false
Ast::Token.valid? [:single] #=> true

Parameters:

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ast_ast/token.rb', line 21

def self.valid?(arr)
  if arr.is_a? Array
    if arr.nil? || arr.size > 2 || arr.size == 0
      false
    elsif !arr[0].is_a?(Symbol)
      false
    else
      true
    end
  elsif arr.is_a? Token
    true
  else
    false
  end
end

Instance Method Details

#inspectObject

Make #inspect show something a bit prettier



72
73
74
# File 'lib/ast_ast/token.rb', line 72

def inspect
  self.to_s
end

#to_aArray

Turn the Token to an Array.

Examples:


Ast::Token.new(:test, "str").to_a
#=> [:test, "str"]

Returns:

  • (Array)


63
64
65
66
67
68
69
# File 'lib/ast_ast/token.rb', line 63

def to_a
  if @value.nil?
    [@type]
  else
    [@type, @value]
  end
end

#to_sString

Turn the Token to a String, similar to an array.

Examples:


Ast::Token.new(:test, "str").to_s
#=> <:test "str">

Returns:

  • (String)


46
47
48
49
50
51
52
# File 'lib/ast_ast/token.rb', line 46

def to_s
  if @value.nil?
    "<#{@type.inspect}>"
  else
    "<#{@type.inspect}, #{@value.inspect}>"
  end
end