From: Phrogz Date: 2007-11-07T01:30:24+09:00 Subject: Re: why return gives error when used with ? : Others have pointed out that (in this particular example) it's foolish to branch on a boolean value only to return that particular value as a new literal, so here's a modified test showing the fastest way - just let the boolean value return itself. require 'benchmark' def ternary_return1( x ) return ( x==5 ? true : false ) end def ternary_return2( x ) x==5 ? (return true) : (return false) end def if_return1( x ) return (if x == 5 true else false end) end def if_return2( x ) if x == 5 return true else return false end end def ternary_expression( x ) x == 5 ? true : false end def if_expression( x ) if x == 5 true else false end end def boolean_expression( x ) x == 5 end def return_boolean( x ) return x == 5 end values = (1..8).to_a * 1_000_000 method_names = %w| ternary_return1 ternary_return2 if_return1 if_return2 ternary_expression if_expression boolean_expression return_boolean | Benchmark.bmbm{ |x| method_names.each{ |name| meth = method( name ) x.report( name ){ values.each{ |n| meth.call( n ) } } } } Rehearsal ------------------------------------------------------ ternary_return1 12.125000 0.000000 12.125000 ( 12.172000) ternary_return2 11.750000 0.000000 11.750000 ( 11.812000) if_return1 11.797000 0.000000 11.797000 ( 11.813000) if_return2 11.453000 0.000000 11.453000 ( 11.484000) ternary_expression 10.516000 0.000000 10.516000 ( 10.578000) if_expression 11.218000 0.000000 11.218000 ( 11.250000) boolean_expression 9.719000 0.000000 9.719000 ( 9.782000) return_boolean 10.797000 0.000000 10.797000 ( 10.812000) -------------------------------------------- total: 89.375000sec user system total real ternary_return1 11.578000 0.000000 11.578000 ( 11.625000) ternary_return2 12.141000 0.000000 12.141000 ( 12.188000) if_return1 11.765000 0.000000 11.765000 ( 11.812000) if_return2 12.031000 0.000000 12.031000 ( 12.078000) ternary_expression 10.969000 0.000000 10.969000 ( 10.999000) if_expression 11.078000 0.000000 11.078000 ( 11.125000) boolean_expression 10.093000 0.000000 10.093000 ( 10.125000) return_boolean 11.141000 0.000000 11.141000 ( 11.188000)