Die Programmiersprache Ruby

Blog| Forum| Wiki  

Diese Seite zeigt Implementierungen von Extreme

Interpreter Implementierung von cui:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env ruby 


INPUT = 'Factor:_ ?a% 
Until:_ ?u% 
 {a _*_ i(1..u) _=_ (a * i)}' 


$vars = {} 
$out = "" 

class Var 
    def initialize(val) 
        @val = val 
    end 
    def to_i 
        Int.new(@val.to_i) 
    end 
    def to_s 
        Str.new(@val.to_s) 
    end 
    attr_accessor :val 
end 

class Str < Var 
    def +(v) 
        @val + v.to_s 
    end 
    def *(v) 
        @val * v.to_i 
    end 
end 

class Int < Var 
    def +(v) 
        @val + v.to_i 
    end 
    def *(v) 
        @val * v.to_i 
    end 
    def /(v) 
        @val / v.to_i 
    end 
    def -(v) 
        @val - v.to_i 
    end 
end 



def out_err err 
    puts err 
    exit 
end 

def read_str(str) 
    nstr = str.gsub(/\((\w+)\s*([+\-*\/])\s*(\w+)\)/) { 
        if (t=$vars.fetch($1, $1.to_i)).kind_of?(Integer) or t.kind_of?(Int) 
            v1 = t 
        else 
            out_err "Wrong type of variable!" 
        end 
        if (t=$vars.fetch($3, $3.to_i)).kind_of?(Integer) or t.kind_of?(Int) 
            v2 = t 
        else 
            out_err "Wrong type of variable!" 
        end 
        case $2 
            when '+' then result = v1 + v2 
            when '-' then result = v1 - v2 
            when '*' then result = v1 * v2 
            when '/' then result = v1 / v2 
        end 
    } 
    nstr.split(" ").each { |p| 
        if p =~ /\A\?([A-Za-z])(\%?)/ 
            $vars[$1] = STDIN.gets.chomp 
            $vars[$1] = $vars[$1].to_i if $2 == '%' 
            return 
        end 
        print $vars.fetch(p, p).to_s.gsub("_", " ") 
    } 
    puts 
end 



INPUT.each_line { |code| 
    if code =~ /\A\s(.*)/    # code 
        block = $1 
        if block =~ /\A\{(.*?([A-Za-z]+))\((\w+)(\.\.\.?)(\w+)\)(.*)\}\z/ 
            string = $1 + $6 
            counter = $2 
            rstart = $vars.fetch($3, $3.to_i) 
            rend = $vars.fetch($5, $5.to_i) 
            rtype = $4 
            # analyse range 
            $vars[counter] = Int.new(0) 
            range = (rtype == ".." ? (rstart..rend) : (rstart...rend)) 
            for i in range 
                $vars[counter] += 1 
                read_str(string) 
            end 
        end 
    else 
        read_str(code) 
    end 
}