what is the best way to do this in ruby?
if condition
then do a whole bunch of comparisons using >
else
do all the same comparisons except using <
what is the best way to do this in ruby?
if condition
then do a whole bunch of comparisons using >
else
do all the same comparisons except using <
I ended up doing something like this:
def threshold_compare(value1, value2, operation)
if operation == ‘>=’
value1 >= value2
elsif operation == ‘<=’
value1 <= value2
end
end
On 12/04/12 16:29, phil rosenstein wrote:
I ended up doing something like this:
def threshold_compare(value1, value2, operation)
if operation == ‘>=’
value1>= value2
elsif operation == ‘<=’
value1<= value2
end
end
What about just
1.9.2p290 :001 > def threshold_compare(value1, value2, operator=’==’)
1.9.2p290 :002?> value1.send(operator.to_sym, value2)
1.9.2p290 :003?> end
Additionally you could add a check for valid operators and see if value1
responds to the method if you wanted. Something like
if [:==, :>, :<, :>=, :<=].include? operator.to_sym &&
value1.respond_to? operator.to_sym
… and maybe raise an ArgumentError with a helpful message if the
conditions aren’t met.
You might not need to be paranoid about it depending on your context.
You could also ‘bake’ the valid operators array into a variable
somewhere to cut some overhead.
Sam
Hi,
You can use the generalized comparision operator <=>, which returns -1,
0 or 1 depending on the order of the operands. If you set the result for
the operation, you can force it to either do “>” comparisons or “<”
comparisons:
comparison_result =
condition ? 1 : -1
1 <=> 3 == comparison_result
4 <=> 2 == comparison_result
However, the “send” solution is probably easier to understand:
compare =
condition ? :> : :<
1.send compare, 3
4.send compare, 2
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs