From: Dave Burt Date: 2006-05-26T16:09:23+09:00 Subject: Re: Method '!=' Victor Shepelev wrote: > > > > > So, other question: is there way for uniform compare objects by some > > > > > operator? (where operator is either == or != or <, or even include?) > > > The point was to do things like this: > > > > > > def filter(object, op, criteria) > > > object.send op, criteria > > > end > > > > > > filter 'a', :==, 'b' > > > filter 'Ruby', :include?, 'Ru' > > > filter 110, :<, 15 > > > > > > #filter 'a', :!=, 'b' <== doesn't work! :( > > OK, some more pieces of puzzle :) > > 1. really, the former is used as bunch of filters: > > Request.filter [ > [:base_type, :==, 'cpu'], > [:fullname, :include?, 'Intel'], > [:frequency, :>, 2300] > ] > > 2. I'm planning inside Request to do the following: > a) search some pre-fetched array (through Array#select) > b) so some additional request to database > > For (a), filter as lambda is good; but for (b), I need some format I can > convert into plain SQL. From ZenSpider's Ruby QuickRef, with a couple of corrections: http://www.zenspider.com/Languages/Ruby/QuickRef.html#22 Operators by Precedence: :: . [] ** -(unary) +(unary) ! ~ * / % + - << >> & | ^ > >= < <= <=> == === != =~ !~ && || .. ... =(+=, -=...) not and or All of the above are just methods except these: =, .., ..., !, not, &&, and, ||, or, !=, !~, :: In addition, assignment operators(+= etc.) are not user-definable. You may want to transform &&, || and != into a certain proc and a certain other string for use in SQL. Perhaps something like this: op = Hash.new do |h, k| { :sql => k, :proc => proc {|obj, *args| obj.send(k, *args) } } end op["&&"] = {:sql => " AND ", :proc => proc {|l,r| l && r } } op["||"] = {:sql => " OR ", :proc => proc {|l,r| l || r } } op["!="] = {:sql => " <> ", :proc => proc {|l,r| l != r } } op["=="] = {:sql => " = ", :proc => proc {|l,r| l == r } } op[">"][:sql] #=> ">" op[">"][:proc].call(2, 1) #=> true Cheers, Dave