Topic: Ruby Operator


I've seen some used operators in ruby which I still don't really know and I don't seem to find a real explanation for what they exactly do, so I thought you might be able to help me out.

What exactly do operators like do:


I know || means 'logical or' and && means 'locigal and' and the '=' is an assignment, so they must be a combination of first comparing something and then assigning the value, but I somehow don't get the gist of it smile

Thanks for help!

Re: Ruby Operator

The ||= is a classic Ruby idiom. Anything that is either nil or false is falsy, and anything else is truthy. So the following

def get_list
  @my_array ||= []

will either return the contents of @my_array, or an empty list if it is nil. &&= works the same, but is probably of less practical value than ||=

Re: Ruby Operator

Ahh... So what '||=' basically does is:

if !@my_array
  @my_array = []
  # @my_array holds the value it has had before

But your example would also work this way, right?

def get_list
  @my_array || []

But the difference is that in your example the empty array is being assigned to @my_array and @my_array is returned, while in my example the [] itself is returned... Is that correct?

Thanks a lot!

Last edited by Vapire (2010-08-17 09:32:41)

Re: Ruby Operator


Re: Ruby Operator


I come to love this language smile

Thank you very much!