2

I was reading over some code and saw a method being defined in the following way (Ruby):

class BaseQuery
  def |(other)
    ChainedQuery.new do |relation|
      other.call(call(relation))
    end
  end
end

I've tried searching ruby docs, as well as SO, but can't find examples of "|" being used at the beginning of a method definition. Can someone please explain the purpose of beginning a method definition with "|" and the effect that it has on that method ?

Thank you so much, any insight would be much appreciated.

frostini
  • 175
  • 10
  • Possible duplicate of [In Ruby, what are the vertical lines?](https://stackoverflow.com/questions/3545870/in-ruby-what-are-the-vertical-lines) – Oliver Charlesworth Nov 08 '17 at 23:33
  • Can you refer a link where you find such sample? – AntonTkachov Nov 08 '17 at 23:36
  • 1
    @OliverCharlesworth That post is for the pipes simply containing block parameters...such as | x , y | . In this case, they use a single vertical bar as the first character for defining a method, which is considerably different. – frostini Nov 08 '17 at 23:39
  • 1
    @AntonTkachov this is the article https://www.sitepoint.com/7-design-patterns-to-refactor-mvc-components-in-rails/ . In the Query Objects section specifically – frostini Nov 08 '17 at 23:40
  • 1
    omg, i think it's just the method's name...yeah ? I was thinking maybe it had something to do with alternative block or lambda notations – frostini Nov 08 '17 at 23:41
  • 1
    @frostini yes, exactly. – Stefan Nov 08 '17 at 23:47
  • 1
    Funny thing :) To be honest I've also haven't got it when saw it for the first time :) – AntonTkachov Nov 08 '17 at 23:52

2 Answers2

2

'"|" being used at the beginning of a method definition' indeed defines the method |.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 2
    Right answer. In other words, operators like _Bitwise or_ or _Array union_ are Ruby methods, predefined in some classes. Here `class BaseQuery` defines the `or` operator with parameter `(other)` for it's own use. – BernardK Nov 09 '17 at 08:00
1

In the site you linked to, the example method can be read as pipe rather than |.

For more information, see What are the restrictions for method names in Ruby?

anothermh
  • 9,815
  • 3
  • 33
  • 52