proposal: let kind_of take more arguments

G

Gavin Kistner

Gavin said:
unless [Zero, One].any? {|klass| choice.kind_of?(klass)}

Or shorter

unless [Zero, One].any?(&choice.method:)kind_of?)


Or, as I noted on the RCR:

unless ([Zero,One] & choice.class.ancestors).length>0

For the curious, here's how the three methods above stack up in terms of
performance (see below stupid test code that should probably be using
Ruby's built-in profiling for the results). The summary is: The third
method above is generally faster, unless there's a high probability that
a match will be found early on in your test list, in which case the
first example above is fastest.


-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_

instance = ValidForm::Text.new('userName');
testList = [
{:classes =>
[Array,ValidForm::OptionSet,Module,Method,Fixnum],
:name=>'No match is found:'},
{:classes =>
[Array,ValidForm::OptionSet,Module,Method,Object],
:name=>'Match at end of list:'},
{:classes =>
[Object,Array,ValidForm::OptionSet,Module,Method],
:name=>'Match at start of list:'}
]

n=50000

puts instance.class.ancestors.join(',')

testList.each{ |test|
classes=test[:classes]
puts test[:name]
s1 = Time.now
n.times{
(classes & instance.class.ancestors).length>0
}
s2 = Time.now
printf "Using set intersection: %.2f\n",(s2-s1)


s1 = Time.now
n.times{
classes.any?{ |k| instance.kind_of?(k) }
}
s2 = Time.now
printf " Using explicit block: %.2f\n",(s2-s1)

s1 = Time.now
n.times{
classes.any?(&instance.method:)kind_of?))
}
s2 = Time.now
printf "Passing kind_of? block: %.2f\n",(s2-s1)
puts
}

OUTPUTS

ValidForm::Text,ValidForm::Field,Object,Kernel

No match is found:
Using set intersection: 1.17
Using explicit block: 1.38
Passing kind_of? block: 2.24

Match at end of list:
Using set intersection: 1.18
Using explicit block: 1.21
Passing kind_of? block: 2.27

Match at start of list:
Using set intersection: 1.19
Using explicit block: 0.46
Passing kind_of? block: 1.26
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,143
Messages
2,570,822
Members
47,368
Latest member
michaelsmithh

Latest Threads

Top