Created
April 5, 2013 19:14
-
-
Save codebender/5321839 to your computer and use it in GitHub Desktop.
Arrayize! convert any non-array object to an array. Leave any existing array alone.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ```ruby | |
| # Arrayize! convert any non-array object to an array. Leave any existing array alone. | |
| def arrayize(object) | |
| return [object] unless object.is_a?(Array) | |
| object | |
| end | |
| def arrayize2(object) | |
| Array.new(1) { object }.flatten | |
| end | |
| def enumerize(object) | |
| object.enum_for | |
| end | |
| ``` | |
| * Benchmark results | |
| for object being an array already and an object that is a hash | |
| puts Benchmark.measure { 1_000_000.times { |t| arrayize(['blah']) } } | |
| 0.460000 0.000000 0.460000 ( 0.458994) | |
| puts Benchmark.measure { 1_000_000.times { |t| arrayize({test: 'blah'}) } } | |
| 1.060000 0.010000 1.070000 ( 1.064968) | |
| puts Benchmark.measure { 1_000_000.times { |t| arrayize2(['blah']) } } | |
| 2.110000 0.000000 2.110000 ( 2.112629) | |
| puts Benchmark.measure { 1_000_000.times { |t| arrayize2({test: 'blah'}) } } | |
| 2.350000 0.010000 2.360000 ( 2.356239) | |
| puts Benchmark.measure { 1_000_000.times { |t| enumerize(['blah']) } } | |
| 0.800000 0.000000 0.800000 ( 0.803645) | |
| puts Benchmark.measure { 1_000_000.times { |t| enumerize({test: 'blah'}) } } | |
| 1.270000 0.000000 1.270000 ( 1.269319) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment