#!/usr/bin/env ruby # x is a global variable which can be accessed from other namespaces # ex: if we were in the namespace ONE::TWO then access 'a' with ONE::TWO::W # it is mandatory for globals to be uppercased global W = 2 # fibonacci sequence with ret value cached func fibonacci(n) is cached { n < 2 ? n : __FUNC__(n - 1) * __FUNC__(n - 2) } # forever loop forever { "Hello World".say } # async forever loop async forever { ["Hello", "World"].each{ .uc.shuffle + _ } } # func fibonacci asyncronously async fibonacci(10) # Working with blocks LABEL: { say "block one" # recurse to the current block _BLOCK_ if "one".shuffle(3) = "one" # recurse to the current block too _LABEL_ if "one".shuffle(3) = "one" { say "block two" # recurse to LABEL _LABEL_ if "two".shuffle(4) = "two" # recurse to the current block _BLOCK_ } } ## Numbers 3.times{ ... } # ...: unimplemented ## Hash # declare a hash and store it in a lexically scope variable var bhash = { one = 2, two = 1 } # or var ahash = Hash.new( 2 = two, 3 = "this three", one = 1, ) # can replace '->' with ',' # declaring a code/block var code = { let(k, v) = (_[0], _[2]) say "#k, #{v isa Num ? v + 1 : v.uc }" } code(k, v) foreach k,v in ahash ahash.each_kv{ a.say; b.say } ahash.each_kv -> a, b { a.say b.say } # _ is a topic variable hash.keys{ (_ + .lc) }.each{ .say } hash.keys -> a { (a + a.lc) } ahash{one}.say # accessing elements ahash{one, 2, 3}.each{ ... } # returns an array ahash{qw(one 2 3)} = ["One", 2, "ThReE"] # change values var key = "Hello" say ahash{key} if ahash.exists(key) del key # delete lexical var 'key' ## Arrays var array = ["one", 2, 3] # or var barray = Array.new("one", 2, 3) array.say array.each{ ... }.grep{ ... } var r = (3..4).map{ .say } # returns an array of values ranging from 3 to 4 # access values barray[0].say array[2..4].each({...}) # lvalue array[0..1] = qw(i j) 'a'..'z'.each{ ahash.exists(_) && .say } ## Complex data structures var wtf = { one = [ { two = 3, three = 4 }, [qw(a b c d)] ], two = do { ... }, three = True ? [ { one = 1, two = 2 } ] : do { ... }, } var b = [wtf, True] ## Working with Files const file = "/path/to/file" .each_line{ .uc.say } # open file "a" for reading if exists and return the File object <>.each_line{ ... } # read from standard input # classes class Person { ... } class Student is Person { has class is rw has notes is ro # multiple dispatch method get_nodes(v) { self.notes.each{_ > v} } } # flow constructs var k = qw(one two three) for k -> a { a.uc.say } for k -> a is rw { a.shuffle } for k { .uc.say } var b = { one = 1, two = 2, three = 4, } for b -> k, v { (a + ':' + b).say }