Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby TrueClass single pipe

Tags:

ruby

From documentation: http://ruby-doc.org/core-2.2.0/TrueClass.html#method-i-7C

true |  puts("or")
true || puts("logical or")

# produces:

or
  • Could you explain when "single pipe" is useful?
  • What's the difference?

(only in TrueClass context (not Array or Fixnum context )

like image 892
itsnikolay Avatar asked Dec 26 '14 15:12

itsnikolay


1 Answers

It is useful when you do not need eager evaluation of or statement.

For example, if you have some methods, that do something useful and returns true/false as a result, and have another method that should be called only if any of those methods returns true, it is useful to use |:

def action1
  # do something, returns true/false
end

def action2
  # do something, returns true/false
end

def result_action
  # do something 
end

result_action if action1 | action2

If you use logical || instead then if action1 returns true, action2 will not be called (result_action will be invoked though)

like image 200
mikdiet Avatar answered Sep 18 '22 14:09

mikdiet