OSDN Git Service

Regular updates
[twpd/master.git] / goby.md
1 ---
2 title: Goby
3 layout: 2017/sheet
4 prism_languages: [ruby]
5 weight: -3
6 updated: 2018-12-06
7 category: Ruby
8 intro: |
9   Goby's language design is based on Ruby language's, slim and shaped up. Differences in syntax between them is very small.
10 ---
11
12
13 ## Getting started
14
15 ### Hello world
16 {: .-prime}
17
18 #### hello.gb
19 {: .-file}
20
21 ```ruby
22 class Greet
23   attr_accessor :audience, :head, :tail
24   
25   def initialize
26     @head = "Hello, "
27     @tail = "!"
28   end
29
30   def name
31     audience.name
32   end
33
34   def say
35     puts head + name + tail
36   end
37 end
38
39 module MyName
40   attr_reader :name
41
42   def initialize
43     @name = self.class.to_s
44   end
45 end
46
47 class World
48   include MyName
49 end
50
51 greet = Greet.new
52 greet.audience = World.new
53 greet.say
54 ```
55
56 Then run:
57
58 ```bash
59 $ goby hello.gb
60 #=> Hello, World!
61 ```
62
63 ### REPL (igb)
64
65 ```bash
66 $ goby -i
67 ```
68
69 * `reset`: reset the VM
70 * `exit`: exit REPL
71 * `help`: show help
72 * ctrl-c: cancel the block entered, or exit (on top level)
73
74 See [igb manual & test script](https://github.com/goby-lang/goby/blob/master/igb/manual_test.md). You can use `readline` features such as command history by arrow keys.
75
76 ## Variables
77 {: .-three-column}
78
79 ### Local variable
80
81 ```ruby
82 zip101 = "233-7383"
83 magic_number = 42
84 ```
85
86 Should be "`[a-z][a-z0-9_]+`"(snake_case).
87
88 ### Instance variable
89
90 ```ruby
91 module State
92   def initialize(state)
93     @state = state      # declaring an instance variable by assignment
94   end
95   def show
96     @state              # accessible from other instance methods
97   end
98 end
99
100 state = State.new "success"
101 state.show
102 #=> success
103 ```
104
105 Should be "`@[a-z][a-z0-9_]+`"(snake_case).
106
107 ### Multiple assignment
108
109 ```ruby
110 # array literal
111 a, b, c = [1, 2, 3]
112
113 # array with '*'
114 a = [1, 2, 3]
115 x, y, z = *a
116
117 # array literal with '*'
118 a, b, c = *[1, 2, 3]
119
120 # bare assignment: unsupported
121 a, b, c = 1, 2, 3  #=> unexpected 3 Line: 0
122 ```
123
124 ### Black hole variable
125
126 ```ruby
127 # '_' is write-only
128 a, _ = [1, 2]
129 ```
130
131 ### Class variable
132
133 Unsupported.
134
135 ### Global variable
136
137 Unsupported.
138
139 ## Method definition
140
141 ### Method definition and calling
142
143 ```ruby
144 def foo_bar?(baz)
145   if baz == "Hi, Goby!"
146     true
147   else
148     false
149   end
150 end
151
152 foo_bar? "Hi, Goby!" #=> true
153 ```
154
155 Method name should be "`[a-z][a-z0-9_]+\??`" (snake_case). You can omit the trailing "`()`" only if no parameters are taken. Trailing using "`!`" is **unsupported**.
156
157 ### Order of method parameter
158
159 ```ruby
160 def foo(normal, default="value", hash={}, ary=[], keyword:, keyword_default:"key", *sprat)
161 end
162 ```
163
164 If a default value is provided to a parameter, the parameter can be omitted when calling. `()` can be omitted. The order of parameters in method definition is restricted as follows:
165
166 1. **normal parameters** (like `a`)
167 2. **normal parameters with default value** (like `a=1`)
168 3. **optional parameters** (array or hash, like `ary=[]` or `hs={}`)
169 4. **keyword parameters** (like `kwd:`) 
170 5. **keyword parameters with default value** (like `kwd: 1` or `ary: [1,2,3]` or `hsh: {key: "value"}`)
171 6. **splat parameters** (like `*sp`)
172
173 Or you will receive an error.
174
175 ### Keyword parameter (WIP)
176
177 ```ruby
178 def foo(process:, verb: :GET, opt:{ csp: :enabled }, ary: [1, 2, 3])
179 end
180 ```
181
182 ### Returning value
183
184 ```ruby
185 PI = 3.14
186 def area(radius)
187   radius * PI      # returns the result of evaluation
188 end
189
190 area 6             #=> 18.84
191 ```
192
193 ### Returning multiple value
194
195 ```ruby
196 def my_array
197   [1, 2, 3]
198 end
199
200 my_array   #=> [1, 2, 3]
201 ```
202
203 ### Instance method
204
205 ```ruby
206 module Foo
207   def bar       # defining instance method
208     puts "bar"
209   end
210   
211   def baz(count, email: "goby@example.com")
212     count.times do
213       puts email
214     end
215   end
216 end
217
218 foo = Foo.new
219 foo.bar     #=> bar
220 foo.baz(3)  #↓
221 goby@example.com
222 goby@example.com
223 goby@example.com
224 ```
225
226 ### Singleton method #1
227
228 ```ruby
229 str = "Goby"
230 def str.foo     #1 singleton method on the object
231   self * 2
232 end
233
234 str.foo
235 #=> GobyGoby
236 ```
237
238 ### Singleton method #2
239
240 ```ruby
241 module Foo
242   def self.bar  #2 singleton method with `self.`
243     92
244   end
245 end
246 ```
247
248 ### Singleton method #3
249
250 ```ruby
251 module Foo  
252   def Foo.bar   #3 singleton method with a class name (unrecommended)
253     88
254   end
255 end
256 ```
257
258 ### Singleton method #4
259
260 ```ruby
261 module Foo end
262
263 def Foo.bar     #4 singleton methods outside the Foo
264   9999
265 end
266
267 Foo.bar #=> 9999
268 ```
269
270 ### Attribute accessor method
271
272 ```ruby
273 class Foo
274   attr_accessor :bar, :baz
275
276   def initialize
277     @bar = 42
278     @baz = 99
279   end
280 end
281
282 foo = Foo.new
283
284 foo.bar = 77
285 foo.baz = 88
286 ```
287
288 You can use the following shorthands to declare attribute accessor methods in classes/modules:
289
290 * `attr_accessor`
291 * `attr_reader`
292 * `attr_writer`
293
294 ### Private method (to be implemented)
295
296 ```ruby
297 class Foo
298   def bar
299     42
300   end
301   
302   def _baz  # leading '_' means private method
303     99
304   end
305 end
306 ```
307
308 ## Module/Class definition
309 {: .-three-column}
310
311 ### Module definition and `include`
312
313 ```ruby
314 module Foo
315   def foo
316     "Foo's instance method"
317   end
318 end
319
320 class Bar
321   include Foo   # to include Foo
322 end
323
324 Bar.new.foo     #=> Foo's instance method
325 ```
326
327 Module names should be "`[A-Z][A-Za-z0-9_]+`" (UpperCamelCase). Modules cannot be inherited.
328
329 ### Module definition and `extend`
330
331 ```ruby
332 module Foo
333   def foo
334     "Foo's instance method will be a singleton method"
335   end
336 end
337
338 class Bar
339   extend Foo   # to extend Foo  
340 end
341
342 Bar.foo        #=> Foo's instance method will be a singleton method
343 ```
344
345 `extend` is to use the instance methods in the specified modules as **singleton methods** in your class or module. 
346
347 ### Module instantiation
348
349 ```ruby
350 module Foo   #module definition
351   def foo   
352     99
353   end
354 end
355
356 Foo.new.foo  #=> 99
357 ```
358
359 Actually, Goby's module can be even **instantiated** via "`new`" like "`Foo.new`".
360
361 ### Class definition and inheritance
362
363 ```ruby
364 class Foo       # class definition
365   def bar
366     99
367   end
368 end
369
370 class Baz < Foo # inheritance
371 end
372
373 Baz.new.bar  #=> 99
374 ```
375
376 Class names should be "`[A-Z][A-Za-z0-9]+`" (UpperCamelCase). Inheritance with "`<`" is supported.
377
378 ### Constants
379
380 ```ruby
381 HTTP_ERROR_404 = 404
382 HTTP_ERROR_404 = 500    # error
383 ```
384
385 Constants should be "`[A-Z][A-Za-z0-9_]+`" (UPPER_SNAKECASE). Constants are **not reentrant** and the scope is **global**.
386
387 ### Redefining class/modules
388
389 ```ruby
390 class Foo
391   def bar
392     99
393   end
394 end
395
396 class Foo
397   def bar  # redefining is possible
398     77
399   end
400 end
401 ```
402
403 ### Namespaces
404
405 ```ruby
406 class Foo
407   module Bar
408     MAGIC = 99
409     def baz
410       99
411     end
412   end
413 end
414
415 Foo::Bar.new.baz     # Use '::' for namespacing
416 Foo::Bar::MAGIC      # Use '::' for namespacing
417 ```
418
419 ## Load library
420
421 ### `require`
422
423 ```ruby
424 require("uri")   # to activate URL class
425
426 u = URI.parse("http://example.com")
427 u.scheme   #=> "http"
428 ```     
429
430 ### `require_relative`
431
432 ```ruby
433 require_relative("bar")  # loading the local bar.gb
434
435 class Foo
436   def self.bar(x)
437     Bar.foo do |ten|
438       x * ten
439     end
440   end
441
442   def self.baz
443     yield(100)
444   end
445 end
446 ```
447
448 ## Literal
449 {: .-three-column}
450
451 ### Keyword
452
453 `def`, `true`, `false`, `nil`, `if`, `elsif`, `else`, `case`, `when`, `return`, `self`, `end`, `while`, `do`, `yield`, `get_block`, `next`, `class`, `module`, `break`
454
455 ### String literal
456
457 ```ruby
458 "double quote"
459 'single quote'
460 ```
461
462 Double and single quotation can be used.
463
464 ### Symbol literal
465
466 ```ruby
467 :symbol           # equivalent to "symbol"
468 { symbol: "value" }
469 ```
470
471 Goby's symbol (using `:`) is always `String` class.
472
473 ### Numeric literal
474
475 ```ruby
476 year   =  2018   # Integer
477 offset = -42     # Integer
478 PI     = 3.14    # Float
479 G      = -9.8    # Float
480 ```
481
482 ### Array literal
483
484 ```ruby
485 [1, 2, 3, "hello", :goby, { key: "value"}]
486 [1, 2, [3, 4], 5, 6]
487 ```
488
489 ### Hash literal
490
491 ```ruby
492 h = { key: "value", key2: "value2" }
493 h[:key2]   #=> value2
494 ```
495
496 Hash literal's keys should always be **symbol literals**. 
497
498 ### Range literal
499
500 ```ruby
501 (1..10).each do |x|    # '..' represents a range
502   puts x*x
503 end
504 ```
505
506 ### Boolean and `nil`
507
508 ```ruby
509 true       # Boolean class
510 false      # Boolean class
511 nil        # Null class
512
513 !nil  #=> true
514 ```
515
516 Any objects except `nil` and `false` will be treated as `true` on conditionals.
517
518 ## Operator
519
520 ### Arithmetic/logical/assignment operators
521
522 ```ruby
523 +           # unary
524 **          # power
525 -           # unary
526 * / %       # multiplication, division, modulus
527 + -         # addition, subtraction
528 !           # logical inversion
529 > >= < <=   # inequality comparison
530 == !=       # equality comparison, negative comparison
531 &&          # logical AND
532 ||          # logical OR
533 += -=       # shorthand of addition/subtraction
534 =           # assignment
535 ```
536
537 *Priority of operators are TBD
538
539 ### Other operators
540
541 ```ruby
542 ()          # chaning priority of interpretation
543 []          # array literal
544 *           # multiple assignment
545 ..          # range
546 ```
547
548 *Priority of operators are TBD
549
550 ### Delimiter
551
552 ```ruby
553 class Foo; end   # ';' to delimit
554
555 class Bar end    # recommended
556 ```
557
558 ### String interpolation (to be implemented)
559
560 ```ruby
561 puts "Error: #{error_message}"  # double quotation is required
562 ```
563
564 ### Comment
565
566 ```ruby
567 puts "Goby"    # comments
568 ```
569
570 Use the annotations to keep the comments concise.
571
572 - `TODO`
573 - `FIXME`
574 - `OPTIMIZE`
575 - `HACK`
576 - `REVIEW`
577
578 ### I/O
579
580 * `#puts`
581
582 * special constants: `ARGV`, `STDIN`, `STDOUT`, `STDERR`, `ENV` 
583
584 ## Flow control
585 {: .-three-column}
586
587 ### `if`, `else`, `elsif`
588
589 ```ruby
590 def foo(str)
591   if str.size > 10
592     puts "too big!"
593   elsif str.size < 3
594     puts "too short!"
595   else
596     puts "moderate"
597   end
598 end
599 ```
600
601 `then` is **not** supported.
602
603 ### Break
604
605 ```ruby
606 def foo(tail)
607   (5..tail).each do |t|
608     if t % 2 == 0 && t % 5 == 0
609       puts "ouch!"
610       break       # finish the block
611     else
612       puts t
613     end
614   end
615   puts "out of the block"
616 end
617
618 foo 20
619 #=> 5 6 7 8 9
620 #=> ouch!
621 #=> out of the block
622 ```
623
624 ### Case
625
626 ```ruby
627 def foo(str)
628   case str
629   when "Elf"
630     puts "You might be Aragorn II!"
631   when "Aragorn"
632     puts "Long time no see, Aragorn!"
633   when "Frodo", "Sam", "Gandalf"
634     puts "One of us!"
635   else
636     puts "You're not yourself"
637   end
638 end
639 ```
640
641 ### While
642
643 ```ruby
644 decr = 10
645 while decr do
646   if decr < 1
647     break
648   end
649   puts decr
650   decr -= 1
651 end
652 ```
653
654 `while`, conditional and a `do`/`end` block can be used for a loop.
655
656 ### Rescue
657
658 Under construction. Join [#605](https://github.com/goby-lang/goby/issues/605).
659
660 ## Block
661 {: .-three-column}
662
663 ### Block
664
665 ```ruby
666 def foo(ary: [1, 2, 3])
667   ary.each do |s|      # start of the block with |block variable|
668     puts s
669   end                  # end of the block
670 end
671 ```
672
673 `{ }` cannot be used for forming a block.
674
675 ### `yield`
676
677 ```ruby
678 def foo
679   yield(10)  # executes the block given
680 end
681
682 foo do |ten|
683   ten + 20
684 end
685 ```
686
687 ### Block object and `call`
688
689 ```ruby
690 b = Block.new do
691   100
692 end
693
694 b.call  #=> 100
695 ```
696
697 `Block.new` can take a block and then `call`.
698
699 ### Passing a block
700
701 ```ruby
702 def baz
703   1000
704 end
705
706 class Foo
707   def exec_block(block)
708         block.call
709   end
710
711   def baz
712     100
713   end
714 end
715
716 b = Block.new do
717   baz
718 end
719
720 f = Foo.new
721 f.exec_block(b)
722 ```
723
724 ### Passing a block with block arguments
725
726 ```ruby
727 b = Block.new do |arg, offset|
728   arg + 1000 - offset
729 end
730
731 b.call(49, 500) #=> 549
732 ```
733
734 ### Special `get_block` keyword
735
736 ```ruby
737 def bar(block)
738   # runs the block object and the block arg simultaneously
739   block.call + get_block.call
740 end
741
742 def foo
743   bar(get_block) do # passes two blocks to `bar`
744     20
745   end
746 end
747
748 foo do
749   10
750 end
751 ```
752
753 `get_block` is not a method but a **keyword** to retrive a given block argument as a block object. By this, you can pass around or `call` the given block arguments as block objects. 
754
755 ### Closure
756
757 ```ruby
758 count = 0          # the declaration is used
759 b = Block.new do
760   count += 1       # the block looks preserving the `count`
761 end
762
763 class Foo
764   def bar(blk)
765     count = 9      # (does not affect)
766     puts blk.call  # local variable is resolved to the one above
767   end
768 end
769
770 Foo.new.bar b  #=> 1
771 Foo.new.bar b  #=> 2
772 Foo.new.bar b  #=> 3
773 ```
774
775 ## Native class (Primary)
776 {: .-three-column}
777
778 Goby's most "native" classes cannot instantiate with `new` in principle. 
779
780 ### `Object`
781
782 ```ruby
783 Bar.ancestors
784 #» [Bar, Foo, Object]
785 Bar.singleton_class.ancestors
786 #» [#<Class:Bar>, #<Class:Object>, Class, Object]
787 ```
788
789 `Object` is actually just for creating singleton classes. See `Class`.
790
791 * **`Object.methods`**: `!`, `!=`, `==`, `block_given?`, `class`, `exit`, `instance_eval`, `instance_variable_get`, `instance_variable_set`, `is_a?`, `methods`, `nil?`, `object_id`, `puts`, `raise`, `require`, `require_relative`, `send`, `singleton_class`, `sleep`, `thread`, `to_s`, `<`, `<=`, `>`, `>=`, `ancestors`, `attr_accessor`, `attr_reader`, `attr_writer`, `extend`, `include`, `name`, `new`, `superclass`
792
793 * **`Object.new.methods`**: `!`, `!=`, `==`, `block_given?`, `class`, `exit`, `instance_eval`, `instance_variable_get`, `instance_variable_set`, `is_a?`, `methods`, `nil?`, `object_id`, `puts`, `raise`, `require`, `require_relative`, `send`, `singleton_class`, `sleep`, `thread`, `to_s`
794
795 ### `Class`
796
797 ```ruby
798 String.ancestors      #=> [String, Object]
799 ```
800
801 `Class` and `Object`can actually be regarded as the same and you don't need to distinguish them in almost all the cases. 
802
803 * **`Class.methods`**: `<`, `<=`, `>`, `>=`, `ancestors`, `attr_accessor`, `attr_reader`, `attr_writer`, `extend`, `include`, `name`, `new`, `superclass`, `!`, `!=`, `==`, `block_given?`, `class`, `exit`, `instance_eval`, `instance_variable_get`, `instance_variable_set`, `is_a?`, `methods`, `nil?`, `object_id`, `puts`, `raise`, `require`, `require_relative`, `send`, `singleton_class`, `sleep`, `thread`, `to_s`
804
805 ### `String`
806
807 ```ruby
808 puts "Hello" + ' ' + 'world'  #=> Hello world
809 ```
810
811 Fixed to **UTF-8** with mb4 support.
812
813 * **`String.methods`**: `fmt`,
814     * the rest: `Class.methods`
815 * **`"a".methods`**:  `!=`, `*`, `+`, `<`, `<=>`, `==`, `=~`, `>`, `[]`, `[]=`, `capitalize`, `chop`, `concat`, `count`, `delete`, `downcase`, `each_byte`, `each_char`, `each_line`, `empty?`, `end_with?`, `eql?`, `fmt`, `include?`, `insert`, `length`, `ljust`, `match`, `new`, `replace`, `replace_once`, `reverse`, `rjust`, `size`, `slice`, `split`, `start_with`, `strip`, `to_a`, `to_bytes`, `to_d`, `to_f`, `to_i`, `to_s`, `upcase`,
816     * the rest: `Object.new.methods`
817
818 ### `Integer`
819
820 ```ruby
821 37037 * 27      #=> 999999
822 ```
823
824 * **`Integer.methods`**: the same as `Class.methods`
825 * **`1.methods`**: `!=`, `%`, `*`, `**`, `+`, `-`, `/`, `<`, `<=`, `<=>`, `==`, `>`, `>=`, `even?`, `new`, `next`, `odd?`, `pred`, `ptr`, `times`, `to_f`, `to_float32`, `to_float64`, `to_i`, `to_int`, `to_int16`, `to_int32`, `to_int64`, `to_int8`, `to_s`, `to_uint`, `to_uint16`, `to_uint32`, `to_uint64`, `to_uint8`
826     * the rest: `Object.new.methods`
827
828 ### `Array`
829
830 ```ruby
831 [1, "2", :card, [4, 5], { john: "doe" }]
832 ```
833
834 * **`Array.methods`**: the same as `Class.methods`
835 * **`[1].methods`**: `*`, `+`, `[]`, `[]=`, `any?`, `at`, `clear`, `concat`, `count`, `delete_at`, `dig`, `each`, `each_index`, `empty?`, `first`, `flatten`, `include?`, `join`, `last`, `lazy`, `length`, `map`, `new`, `pop`, `push`, `reduce`, `reverse`, `reverse_each`, `rotate`, `select`, `shift`, `to_enum`, `unshift`, `values_at`
836     * the rest: `Object.new.methods`
837
838 ### `Hash`
839
840 ```ruby
841 h = { key: "value" }
842 h = { "key": "value" }  #=> error
843
844 h["key"]  #=> value
845 h[:key]   #=> value
846 ```
847
848 Keys in hash literals should be **symbol literals**, while Hash index can be either string or symbol literals.
849
850 * **`Hash.methods`**: the same as `Class.methods`
851 * **`{ key: "value" }.methods`**: `[]`, `[]=`, `any?`, `clear`, `default`, `default=`, `delete`, `delete_if`, `dig`, `each`, `each_key`, `each_value`, `empty?`, `eql?`, `fetch`, `fetch_values`, `has_key?`, `has_value?`, `keys`, `length`, `map_values`, `merge`, `new`, `select`, `sorted_keys`, `to_a`, `to_json`, `to_s`, `transform_values`, `values`, `values_at`
852     * the rest: `Object.new.methods`
853
854 ### `Range`
855
856 ```ruby
857 (1..10).each do |i|
858   puts i ** 2
859 end
860 ```
861
862 * **`Range.methods`**: the same as `Class.methods`
863 * **`(1..10).methods`**: `!=`, `==`, `bsearch`, `each`, `first`, `include?`, `last`, `lazy`, `map`, `new`, `size`, `step`, `to_a`, `to_enum`
864     * the rest: `Object.new.methods`
865
866 ### `Block`
867
868 ```ruby
869 b = Block.new do
870   100
871 end
872
873 b.call  #=> 100
874 ```
875
876 * **`Block.methods`**: the same as `Class.methods`
877 * **`(Block.new do end).methods`**: `call`
878     * the rest: `Object.new.methods`
879
880 ## Native class (secondary)
881 {: .-three-column}
882
883 ### `Float`
884
885 ```ruby
886 1.1 + 1.1   # => -2.2
887 2.1 * -2.1  # => -4.41
888 ```
889
890 Float literals like `3.14` or `-273.15`. `Float` class is based on Golang's `float64` type.
891
892 * **`Float.methods`**: the same as `Class.methods`
893 * **`3.14.methods`**: `!=`, `%`, `*`, `**`, `+`, `-`, `/`, `<`, `<=`, `<=>`, `==`, `>`, `>=`, `new`, `ptr`, `to_d`, `to_i`
894     * the rest: `Object.new.methods`
895
896 ### `Decimal`
897
898 ```ruby
899 "3.14".to_d            # => 3.14
900 "-0.7238943".to_d      # => -0.7238943
901 "355/113".to_d         
902 # => 3.1415929203539823008849557522123893805309734513274336283185840
903
904 a = "16.1".to_d
905 b = "1.1".to_d
906 e = "17.2".to_d
907 a + b # => 0.1
908 a + b == e # => true
909
910 ('16.1'.to_d  + "1.1".to_d).to_s #=> 17.2
911 ('16.1'.to_f  + "1.1".to_f).to_s #=> 17.200000000000003
912 ```
913
914 Experimental: the size is arbitrary and internally a fraction from Golang's `big.Rat` type. Decimal literal is TBD for now and you can get `Decimal` number via `to_d` method from `Integer`/`Float`/`String`.
915
916 * **`Decimal.methods`**: the same as `Class.methods`
917 * **`(1.1).to_d.methods`**: `!=`, `*`, `**`, `+`, `-`, `/`, `<`, `<=`, `<=>`, `==`, `>`, `>=`, `denominator`, `fraction`, `inverse`
918     * the rest: `Object.new.methods`
919
920 ### `Regexp`
921
922 ```ruby
923 a = Regexp.new("orl")
924 a.match?("Hello World")   #=> true
925 a.match?("Hello Regexp")  #=> false
926
927 b = Regexp.new("😏")
928 b.match?("🤡 😏 😐")    #=> true
929 b.match?("😝 😍 😊")    #=> false
930
931 c = Regexp.new("居(ら(?=れ)|さ(?=せ)|る|ろ|れ(?=[ばる])|よ|(?=な[いかくけそ]|ま[しすせ]|そう|た|て))")
932 c.match?("居られればいいのに")  #=> true
933 c.match?("居ずまいを正す")      #=> false
934 ```
935
936 Using `/ /` is to be implemented.
937
938 * **`Regexp.methods`**: the same as `Class.methods`
939 * **`Regexp.new("^aa$").methods`**: `==`, `match?`
940     * the rest: `Object.new.methods`
941
942 ### `MatchData`
943
944 ```ruby
945 # numbered capture
946 'abcd'.match(Regexp.new('(b.)'))
947 #=> #<MatchData 0:"bc" 1:"bc">
948
949 # named capture
950 'abcd'.match(Regexp.new('a(?<first>b)(?<second>c)'))
951 #=> #<MatchData 0:"abc" first:"b" second:"c">
952
953 # converting to hash
954 » 'abcd'.match(Regexp.new('a(?<first>b)(?<second>c)')).to_h
955 #» { 0: "abc", first: "b", second: "c" }
956 ```
957
958 The number keys in the captures are actually `String` class.The key `0` is the mached string.
959
960 * **`MatchData.methods`**: the same as `Class.methods`
961 * **`'abcd'.match(Regexp.new('(b.)')).methods`**: `captures`, `length`, `new`, `to_a`, `to_h`
962     * the rest: `Object.new.methods`
963
964 ### `File`
965
966 ```ruby
967 f = File.new("../test_fixtures/file_test/size.gb")
968 f.name  #=> "../test_fixtures/file_test/size.gb"
969 ```
970
971 * **`File.methods`**: `basename`, `chmod`, `delete`, `exist?`, `extname`, `join`
972     * the rest: `Class.methods`
973 * **`File.new.methods`**: `basename`, `chmod`, `close`, `delete`, `exist?`, `extname`, `join`, `name`
974     * the rest: `Object.new.methods`
975
976 ## Native class (Golang-oriented)
977 {: .-three-column}
978
979 ### `GoMap`
980
981 ```ruby
982 h = { foo: "bar" }
983 m = GoMap.new(h)    # to pass values to Golang's code
984 h2 = m.to_hash
985 h2[:foo]   #=> "bar"
986 ```
987
988 * **`GoMap.methods`**: the same as `Class.methods`
989 * **`GoMap.new.methods`**: `get`, `set`, `to_hash`
990     * the rest: `Object.new.methods`
991
992 ### `Channel`
993
994 ```ruby
995 c = Channel.new
996
997 1001.times do |i| # i start from 0 to 1000
998   thread do
999         c.deliver(i)
1000   end
1001 end
1002
1003 r = 0
1004 1001.times do
1005   r = r + c.receive
1006 end
1007
1008 r #=> 500500
1009 ```
1010
1011 `Channel` class is to hold channels to work with `#thread`. See `thread`.
1012
1013 * **`Channel.methods`**: the same as `Class.methods`
1014 * **`Channel.new.methods`**: `close`, `deliver`, `new`, `receive`
1015     * the rest: `Object.new.methods`
1016
1017 ## Enumerator & lazy
1018
1019 Pretty new experimental library.
1020
1021 ### `LazyEnumerator`
1022
1023 ```ruby
1024 # creating a lazy enumerator
1025 enumerator = LazyEnumerator.new(ArrayEnumerator.new([1, 2, 3])) do |value|
1026         2 * value
1027 end
1028 result = []
1029
1030 enumerator.each do |value|
1031         result.push(value)
1032 end
1033
1034 result   #=> [2, 4, 6]
1035 ```
1036
1037 A shorthand `#lazy` method is also provided in `Array` and `Range` by now. See "Tips & tricks" below. 
1038
1039 * **`LazyEnumerator.methods`**: the same as `Class.methods`
1040 * **`[1, 2].lazy`**: `each`, `first`, `has_next?`, `initialize`, `map`, `next`
1041     * the rest: `Object.new.methods`
1042
1043 ### `ArrayEnumerator`
1044
1045 ```ruby
1046 iterated_values = []
1047
1048 enumerator = ArrayEnumerator.new([1, 2, 4])
1049
1050 while enumerator.has_next? do
1051         iterated_values.push(enumerator.next)
1052 end
1053
1054 iterated_values   #=> [1, 2, 4]
1055 ```
1056
1057 * **`ArrayEnumerator.methods`**: the same as `Class.methods`
1058 * **`ArrayEnumerator.new([1, 2, 3]).methods`**: `has_next?`, `initialize`, `next`
1059     * the rest: `Object.new.methods`
1060
1061 ### `RangeEnumerator`
1062
1063 ```ruby
1064 iterated_values = []
1065
1066 enumerator = RangeEnumerator.new((1..4))
1067
1068 while enumerator.has_next? do
1069         iterated_values.push(enumerator.next)
1070 end
1071
1072 iterated_values   #=> [1, 2, 3, 4]
1073 ```
1074
1075 * **`RangeEnumerator.methods`**: the same as `Class.methods`
1076 * **`RangeEnumerator.new(1..2).methods`**: `has_next?`, `initialize`, `next`
1077     * the rest: `Object.new.methods`
1078
1079 ## Special class
1080
1081 ### `Boolean`
1082
1083 ```ruby
1084 true.class  #=> Boolean
1085 false.class #=> Boolean
1086 ```
1087
1088 A special class that just to hold `true` and `false`. Cannot be instantiate.
1089
1090 ### `Null`
1091
1092 ```ruby
1093 nil.class   #=> Null
1094 ```
1095
1096 A special class that just to hold `nil`. Cannot be instantiate.
1097
1098 ### `Method`
1099
1100 (A special dummy class that just holds methods defined by Goby code.)
1101
1102 ### `Diggable`
1103
1104 Provides `#dig` method. Currently. `Array` and `Hash` classes' instance can be `Diggable`.
1105
1106 ```ruby
1107 [1, 2].dig(0, 1)  #=> TypeError: Expect target to be Diggable, got Integer
1108 ```
1109
1110 ## Testing framework
1111
1112 ### `Spec`
1113
1114 ```ruby
1115 require "spec"
1116
1117 Spec.describe Spec do
1118   it "fails and exit with code 1" do
1119         expect(1).to eq(2)
1120   end
1121 end
1122
1123 Spec.run
1124 ```
1125
1126 * **`Spec.methods`**: `describe`, `describes`, `instance`, `run`
1127     * the rest: `Object.methods`
1128 * **`Spec.new.methods`**: `describes`, `initialize`, `run`, `session_successful`, `session_successful=`
1129     * the rest: `Hash.new.methods`
1130
1131 ## Tips & tricks
1132
1133 ### Showing methods
1134
1135 ```ruby
1136 » "string".methods
1137 #» ["!=", "*", "+", "<", "<=>", "==", "=~", ">", "[]", "[]=", "capitalize", "chop", "concat", "count", "delete", "downcase", "each_byte", "each_char", "each_line", "empty?", "end_with?", "eql?", "fmt", "include?", "insert", "length", "ljust", "match", "new", "replace", "replace_once", "reverse", "rjust", "size", "slice", "split", "start_with", "strip", "to_a", "to_bytes", "to_d", "to_f", "to_i", "to_s", "upcase", "!", "block_given?", "class", "exit", "instance_eval", "instance_variable_get", "instance_variable_set", "is_a?", "methods", "nil?", "object_id", "puts", "raise", "require", "require_relative", "send", "singleton_class", "sleep", "thread"]
1138 ```
1139
1140 ### Showing class
1141
1142 ```ruby
1143 » "string".class
1144 #» String
1145 ```
1146
1147 ### Showing singleton class
1148
1149 ```ruby
1150 » "moji".singleton_class
1151 #» #<Class:#<String:842352325152>>
1152
1153 » "moji".class.singleton_class
1154 #» #<Class:String>
1155 ```
1156
1157 ### Showing ancestors
1158
1159 ```ruby
1160 » Integer.ancestors
1161 #» [Integer, Object]
1162
1163 » "moji".class.ancestors
1164 #» [String, Object]
1165 ```
1166
1167 ### Showing singleton classes' ancestors
1168
1169 ```ruby
1170 » "moji".class.singleton_class.ancestors
1171 #» [#<Class:String>, #<Class:Object>, Class, Object]
1172 ```
1173
1174 ### Showing object's id
1175
1176 ```ruby
1177 » "moji".object_id
1178 #» 842352977920
1179 ```
1180
1181 ### `#to_json`
1182
1183 ```ruby
1184 h = { a: 1, b: [1, "2", [4, 5, nil]]}
1185 h.to_json         # converts hash to JSON
1186 #=> {"a":1, "b":[1, "2", [4, 5, null]]}
1187 ```
1188
1189 ### Customize `#to_json`
1190
1191 Overwrite the `#to_json` in your class:
1192
1193 ```ruby
1194 class JobTitle
1195   def initialize(name)
1196     @name = name
1197   end
1198
1199   def to_json
1200     { title: @name }.to_json
1201   end
1202 end
1203
1204 class Person
1205   def initialize(name, age)
1206     @name = name
1207     @age = age
1208     @job = JobTitle.new("software engineer")
1209   end
1210
1211   def to_json
1212     { name: @name, age: @age, job: @job }.to_json
1213   end
1214 end
1215
1216 stan = Person.new("Stan", 23)
1217 h = { person: stan }
1218 h.to_json #=> {"person":{"name":"Stan","job":{"title":"software engineer"},"age":23}}
1219 ```
1220
1221 ### Lazy enumeration
1222
1223 To avoid N + 1 query.
1224
1225 ```ruby
1226 enumerator = [1, 2, 3].lazy.map do |value|
1227         2 * value
1228 end
1229 result = []
1230
1231 enumerator.each do |value|
1232         result.push(value)
1233 end
1234
1235 result  #=> [2, 4, 6]
1236 ```     
1237
1238 You can call `#lazy.map` on `Array`, `Range`, or `JSON` objects. 
1239
1240 ## Styling
1241
1242 ### Quick style guide
1243
1244 * UTF-8 should be used.
1245 * Only two spaces `  ` should be used for one indentation.
1246     * Tab cannot be used for indentation.
1247 * For more, follow [RuboCop's style guide](https://github.com/bbatsov/ruby-style-guide) in principle.
1248
1249 ### Document notation
1250
1251 * `Class#instance_method` -- use `#` to represent instance methods in documents
1252 * `Class.class_method`
1253 * `Module.module_method`
1254
1255 ### Syntax highlighting
1256
1257 Ready for Vim and Sublime text. You can also use Ruby's syntax highlighting so far.
1258
1259 ## References
1260
1261 ### Official
1262
1263 * Official site: [https://goby-lang.org/](https://goby-lang.org/)
1264 * Repository: [https://github.com/goby-lang/goby/](https://github.com/goby-lang/goby/)
1265 * DevHints: [https://devhints.io/goby](https://devhints.io/goby) (this page)
1266
1267 ### Readings for Goby developers
1268
1269 * [Write an Interpreter in Go](https://interpreterbook.com/)
1270 * [Nand2Tetris II](https://www.coursera.org/learn/nand2tetris2/home/welcome)
1271 * [Ruby under a microscope](http://patshaughnessy.net/ruby-under-a-microscope)
1272 * [YARV's instruction table](http://www.atdot.net/yarv/insnstbl.html)
1273
1274 ### JP resource
1275
1276 * [Goby: Rubyライクな言語(1)Gobyを動かしてみる](https://techracho.bpsinc.jp/hachi8833/2017_11_10/47787)
1277 * [Gobyの組み込みクラスにメソッドを追加する方法](https://qiita.com/hanachin_/items/efc1c976a4f5749514ef)