Asked  7 Months ago    Answers:  5   Viewed   26 times

What's the difference between the or and || operators in Ruby? Or is it just preference?

 Answers

66

It's a matter of operator precedence.

|| has a higher precedence than or.

So, in between the two you have other operators including ternary (? :) and assignment (=) so which one you choose can affect the outcome of statements.

Here's a ruby operator precedence table.

See this question for another example using and/&&.

Also, be aware of some nasty things that could happen:

a = false || true  #=> true
a  #=> true

a = false or true  #=> true
a  #=> false

Both of the previous two statements evaluate to true, but the second sets a to false since = precedence is lower than || but higher than or.

Tuesday, June 1, 2021
 
hakre
answered 7 Months ago
88

and is the same as && but with lower precedence. They both use short-circuit evaluation.

WARNING: and even has lower precedence than = so you'll usually want to avoid and. An example when and should be used can be found in the Rails Guide under "Avoiding Double Render Errors".

Tuesday, June 1, 2021
 
insomiac
answered 7 Months ago
81

The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.

/mi/ =~ "hi mike" # => 3 
"hi mike" =~ /mi/ # => 3 

"mike" =~ /ruby/ # => nil 

You can place the string/regex on either side of the operator as you can see above.

Friday, July 9, 2021
 
davidb
answered 5 Months ago
60

Yes, single-quoted strings don't process ASCII escape codes and they don't do string interpolation.

name = 'Joe'
greeting = 'Hello, #{name}' # this won't produce "Hello, Joe" 
Sunday, August 15, 2021
 
Karsten
answered 4 Months ago
64

It's the splat operator. You'll often see it used to split an array into parameters to a function.

def my_function(param1, param2, param3)
  param1 + param2 + param3
end

my_values = [2, 3, 5]

my_function(*my_values) # returns 10

More commonly it is used to accept an arbitrary number of arguments

def my_other_function(to_add, *other_args)
  other_args.map { |arg| arg + to_add }
end

my_other_function(1, 6, 7, 8) # returns [7, 8, 9]

It also works for multiple assignment (although both of these statements will work without the splat):

first, second, third = *my_values
*my_new_array = 7, 11, 13

For your example, these two would be equivalent:

p *1..10
p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sunday, September 5, 2021
 
derobert
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share