90 likes | 203 Views
Ruby Expressions & Operators. and other languages… . Method invocation. overloaded operators. Compare to 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}
E N D
Ruby Expressions & Operators and other languages…
Method invocation overloaded operators Compare to 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] • // a.[](0), object a, method []=, arg 0 • // a.[](1), object a,method [], arg 1 • x + y • // x.+(y)
Assignment 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
||= How does this work? Remember short-circuit evaluation? Caveat: lvalue must be nil or false Goal: return array if it exists, or a new one results = results || [] results ||= [] Example of a Ruby idiom
More parallel assignment • 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
Operators infix - most prefix - Scheme unary (1 operand) binary (2 operands) ternary (3 operands) operators • Typical associativity rules • Left to right, except assignment and **, which are right to left • Sometimes unary operators associate right to left • 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?
Ambiguity 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 • 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
Topic Summary • 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