0

I want to create some DRY code by inputting a variable key in the where clause in AR

if I have the field as :email and val as 'my@email.com'

how would I write it in Ruby 2 syntax?

with previous syntax I could write

Model.where(field => val)

which would be Model.where(:email => 'my@email.com')

in Ruby 2 the where can be written as Model.where(email: 'my@email.com')

but how would I use the field variable in this situation?

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • Some thing. `something: value` is just a syntax sugar for `:something => value`. – moonfly Oct 12 '14 at 17:58
  • when the symbol :something is stored in a variable, var => val is possible, but ruby 2 syntax is not possible – Nick Ginanto Oct 12 '14 at 19:19
  • Well, yes, it's just a syntactic sugar. When it's stored in a variable you can do only `variable => val`. But if you specify the symbol directly you can do both `symbol: val` and `:symbol => val`. Now, there are now named arguments in functions in Ruby 2 as well (http://robots.thoughtbot.com/ruby-2-keyword-arguments), but this is not the case. `where(:email => "...")` is just yet another syntactic sugar on top of `where({:email => "..."})`. You can drop `{}` around hash, if it's the last argument. See http://stackoverflow.com/questions/16576477/how-do-functions-use-hash-arguments-in-ruby. – moonfly Oct 13 '14 at 01:37
  • 1
    so, you should still be able to use the old syntax. It's not the use of Ruby 2 named arguments, it;s just the use of Ruby 1.9 fancy hash syntax: http://breakthebit.org/post/8453341914/ruby-1-9-and-the-new-hash-syntax. I guess, if there is a problem, you can just be more explicit: `Model.where({field => val})`. – moonfly Oct 13 '14 at 01:38

0 Answers0