-4

in a case...such as

(10 + 20) * 10
=> 300

the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication.So does it applies to other operators as well.Can i override other operators such as << !...etc

Milind
  • 4,535
  • 2
  • 26
  • 58

2 Answers2

2

yes you can,you can do it like this

class String
  def << str
    self + "*" + str
  end
end

puts "str" << "sss"  
jack-nie
  • 736
  • 6
  • 21
2

When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:

10 + 20 * 10 = 300 

This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask Ruby to perform the same calculation and you get a very different answer:

> 10 + 20 * 10
=> 210

This is a direct result of operator precedence. Ruby has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, Ruby considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.

Overriding Operator Precedence

The precedence built into Ruby can be overridden by surrounding the lower priority section of an expression with parentheses. For example:

> (10 + 20) * 10
=> 300

In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication.

for more info refer this :

I hope this makes you clear to understand :)

Community
  • 1
  • 1
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55