0

I've just written this code, that works although I am not entirely sure why:

scope = scope.where(Sequel.qualify(:meeting_graphs, :id) => query.ids)

I am specifically talking about the hash rocket.

Previously the code was this, which makes perfect sense:

scope = scope.where(id: query.ids)

First thing I do not understand is why it does this not work when I replace the hash rocket with a colon which I thought was the preferred syntax:

scope = scope.where(Sequel.qualify(:meeting_graphs, :id): query.ids)

Sequel.qualify returns an object which also confuses me as I thought it would return a symbol.

Can anyone explain?

dagda1
  • 26,856
  • 59
  • 237
  • 450

3 Answers3

3
  1. New hash syntax works only if key is a literal symbol.

  2. Sequel.qualify returns qualifier object identifying column. It's possible since every object can be a hash key in Ruby.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
1
  • that works although I am not entirely sure why

    As long as Sequel.qualify(:meeting_graphs, :id) is valid, it can be a key of a hash. Any object can be a key of a hash. That is why.

  • why it does this not work when I replace the hash rocket with a colon

    Even if Sequel.qualify(:meeting_graphs, :id) turns out to be a symbol, the colon notation will not work because it is part of a literal notation. It is not a method or a keyword that works on Ruby objects that are already made.

sawa
  • 165,429
  • 45
  • 277
  • 381
0

You are passing a keywords to the function and keywords use Hash syntax.

There are many ways to define hashes in ruby, and in the way you use a function one syntax does not work.

def return_one_symbol
   'one'.to_sym
end

hash_syntax1 = {:one => '1'}
hash_syntax2 = {one: '1'}
p hash_syntax1 # => {:one=>"1"}
p hash_syntax2 # => {:one=>"1"}

hash_syntax1_function = {return_one_symbol => '1'}
hash_syntax2_function = {return_one_symbol: '1'}
p hash_syntax1_function # => {:one=>"1"}
p hash_syntax2_function # => {:return_one_symbol=>"1"}

see this post for more info:

Is there any difference between the `:key => "value"` and `key: "value"` hash notations?

Community
  • 1
  • 1
hirolau
  • 13,451
  • 8
  • 35
  • 47