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
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
yes you can,you can do it like this
class String
def << str
self + "*" + str
end
end
puts "str" << "sss"
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.
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 :)