Report

and other languages… puts “yes” • // global, method of Kernel Math.sqrt 2 • // object Math, method sqrt message.length • // object message, method length, no args a.each {|x| puts x} • // object a, method each, associated block a[0] = a[1] overloaded operators • // a.[](0), object a, method []=, arg 0 • // a.[](1), object a,method [], arg 1 x+y • // x.+(y) Compare to other languages lvalue = rvalue lvalue must be address, rvalue must be value x = 1 x += 1 # but not x++. • Abbreviated assignment pseudooperators x,y,z = 1,2,3 # parallel assignment x=y=0 # chained assignment, right assoc MAX = 5; MAX = 6 # constant not really constant… but Ruby gives warning Goal: return array if it exists, or a new one results = results || [] How does this work? Remember short-circuit evaluation? Caveat: lvalue must be nil or false results ||= [] Example of a Ruby idiom • English idioms: pulling my leg, spill the beans • Programming: means of expressing a recurring construct or simple task. Knowing the idioms associated with a programming language and how to use them is an important part of gaining fluency in that language (wikipedia) x,y = y,x # swap x = y; y = x # sequential, both now same value x = 1,2,3 # x = [1,2,3] x,y = [1,2] # same as x=1; y=2 a,b,c = 1,2 # a=1; b=2; c=nil x, *y = 1,2,3 # x=1; y=[2,3] • * is called splat, can only have one per assignment *x, y = 1,2,3 # x=[1,2]; y=3 infix - most prefix - Scheme unary (1 operand) binary (2 operands) operators Typical associativity rules • Left to right, except assignment and **, which are right to left • Sometimes unary operators associate right to left ternary (3 operands) typical precedence: • parentheses • unary operators • ** (if the language supports it) • *, /, % • +, - • APL is different; all operators have equal precedence and all operators associate right to left, precedence and associativity rules can be overridden with parentheses would this be more or less confusing? 1-6 local variables and method names both start with lower case letter So how does Ruby know? If prior assignment, it’s a variable. Otherwise, method invocation. Conditional Expressions • C-based languages (e.g., C, C++) • Also in Perl, JavaScript and Ruby • An example: average = (count == 0)? 0 : sum / count • Evaluates as if written like if (count == 0) average = 0 else average = sum /count Language • • • • • • • • • • Concepts overloaded operators associativity infix vs prefix arity precedence lvalue/rvalue parallel assignment constants short-circuit evaluation conditional expressions Ruby • Abbreviated assignment pseudooperators • ||= idiom • parallel assignment options • splat