#### Miscellaneous Characteristics of Ruby ## Ruby is a very easy to learn language designed to appeal to both ## beginners and advanced programers. I will leave you to pick up the ## basics (if-elses, for loops, etc...) and concentrate on the more interesting ## and eccentric characteristics of Ruby. # functions. Generally two styles are available: a convenient conventional # form and the lambda form, which allows higher-order programming: def f1(x) print x; # ; is optional x+1 end # end is needed to delineate most constructs, including if-else f2 = lambda {|x| print x; x+1} # ; is needed here to separate statements. f1(3) # conventional application f2[3] # lambda-form application, can also use f2.(3) or f2.call(3) #### Variable names and scope A = 4 # a global variable starts with an upper-case letter a = 5 # a local variable def f3() a = 1 # a local var of f3, not to be confused with external a puts a # prints 1 when called end f3() # prints 1 puts a # prints 5 def f4() a+1 # error when f4 is applied since a is an uninitialized local var end ### static versus dynamic scoping test - need to force multiple levels of scope def G(y) x = 1 # local var within g # return the following lambda expression lambda {|y| x+y} # inside lambda term, x is a free (not local) variable end def F() x = 2 # f has it own var named x g = G(1) # is g lambda y.1+y or lambda y.2+y ??? g[4] end print "scoping test: ", F(), "\n" # prints 5. WHAT DOES THIS MEAN? ########## ### array/lists A = [2,3,5,7,11] A.push(13) # destructive add A.methods # prints list of available methods A.collect {|x| x+1} # map ### non-destructive ops: def car(a) a[0] end def cdr(a) a[1..a.length] end def cons(a,b) [a] + b end ############ ### association lists (hash tables) g = {} # initialize g["A"] = 4.0 g["B"] = 3.0 g["C"] = 2.0 g["D"] = 1.0 g["F"] = 0 g.each_key {|x| puts g[x]} # prints each value stored in table ######### blocks def feo(a,&f) # for-every-other loop i =0 while i 0 yield # calls co-routine, possibly with parameters x -=1 end end xtimes(4) { puts "hello" } # calls xtimes with coroutine