Array::Subindex
Are you tired of The Man getting you down by only letting you use whole integers as array indexes? Who isn't, dude! Seriously, who is The Man anyway?
Now you can get back at "The Man", in Ruby at least:
[1,2,3][0.5] == 1.5
%w[ foo bar baz ][1.3] == "arb"
[8,9][Rational(2,5)] == 8.4
[ [1,2], [3,4] ][0.5] == 2.5
The inspiration:
"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." — Stan Kelly-Bootle
— Usman Masood (@usmanm) December 10, 2013
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
This gem is postumously dedicated to Stan Kelly-Bootle. I would like to think he'd approve of this sort misuse of technology.
Installation
You shouldn't really use this gem. Ever. Really, don't.
Ok, ok, you can use is as long as you promise to never use it in a production environment. Clear? Good.
$ gem install array-subindex
..then..
require 'array/subindex'
..and then go pour yourself a stiff drink because, baby, you're going to need it. In fact, you should make it a double just to be safe.
Usage
This gem overrides the Ruby core Array#[] method. Do I sound crazy yet? Because I should. If a "normal" integer index is used, the method behaves as the untainted Array class would:
[1,2][0] == 1
However, if the method detects that the index passed is not an integer but is still a valid number class, the method will return the correct portions of the appropriate indicies.
In the case of an array of numbers (int, float, real), it gets portions of the adjacent values, adds them, and returns them. For example:
[1,2,3][1.5] == 2.5
# 1/2 of index 2 + 1/2 of index 3
It also works for unequal devisions (e.g. indexes other than 0.5):
[1,2,3][0.25] == 1.25
# 3/4 of index 0 + 1/4 of index 1
In the case of irrational divisions, the results are rounded:
[1,2,3][1.001] == 2.001
You can use other number classes, too:
[8,9][Rational(2,5)] == 8.4
[3,4,5][BigDecimal.new("1.5")] == 4.3
For arrays of strings, a concatination of portions of the values are used:
[ "this", "is", "a", "test" ][0.5] == "isi"
# 1/2 of index 0 ("is") added to half of index 1 ("i")
For unevenly dividable strings, the index is rounded down:
[ "foo", "bar", "baz" ][0.5] == "oob"
BONUS LEVEL
For arrays that contain arrays, hashes, or anything that responds like an array, we will get the appropriate index values in those and then concat or add them as appropriate:
[ [ 1, 2 ], [ 3, 4] ][0.5] == 2.5
# [2] + [3], then 0.5 of result
[ [ "foo", "bar" ], [ "baz", "qux" ] ][0.5] == "arb"
# 1/2 of "bar" (rounded up to 2/3) + 1/2 of "baz" (rounded down to 1/3)
# works with hashes, too!
[ ['foo'], { bar: 'baz' } ][0.5] == 'oobar'
# 1/2 of "foo" round up to 2/3 + hash.to_a -> 1/2 of first value
License
Distributed under the WTFPL license.
Contributing
- Don't. Stop encouraging me to commit sins like this.