Joined January 2013
·

Kelton

Boulder, CO
·
·
·

Thanks. I was just fooling around with this, but that will actually help me out when I get sick of writing MATLAB functions in Ruby or when performance is intolerable.

They keep the same precedence when you do that. You just traded the underlying method.

>> 2 * 2 ** 3 # ** has higher precedence
=> 16
>> 2 * 2 ^ 3
=> 7
>> 2 * (2 ^ 3) # ^ has lower precedence
=> 2

class Fixnum
  alias_method :pow, :**
  alias_method :**, :^
  alias_method :^, :pow
end

>> 2 * 2 ** 3 # ** still has higher precedence
=> 2
>> (2 * 2) ** 3
=> 7
>> 2 * 2 ^ 3 # ^ still have lower precedence
=> 64
>> 2 * (2 ^ 3)
=> 16

Still don't know how (or if) you can change precedence of an operator

Yeah, I wanted to add that as an alias that for **, however ^ has a lesser operator precedence than **. So if you want to use ^, you have to wrap it in parens just about everywhere it is used. I figured that it would just be better to use ** so that you wouldn't have that somewhat confusing problem.

That is, unless anyone knows how to change the precedence of an operator.

Achievements
389 Karma
15,083 Total ProTip Views