Reputation: 11882
I'm trying to map integers to numbers within range (1..7)
. 1
through 7
would be mapped to themselves, 8
to 1
, 14
to 7
, and so on.
The obvious candidate to do this is the modulo method %
. However, 7 % 7
gives 0
, which I do not want.
One can write the following method:
def int_map i
(x = i % 7) == 0 ? 7 : x
end
I feel that there should be a better, more succinct way to do this. Is there? And how?
Upvotes: 1
Views: 648
Reputation: 11882
Her's another solution. Quite easy to understand.
[7,1,2,3,4,5,6][i % 7]
Without specifying the array in full, you can do
(1..7).to_a.rotate(-1)[i % 7]
Upvotes: 0
Reputation: 11882
Here's another solution, without using modulo. The downside is that all this math makes confusing code.
i - (i - 1) / 7 * 7
Upvotes: 0
Reputation: 18762
Here is one more way to do this:
(1..7).to_a.rotate(i).last
Sample program given below:
def int_map i
[1,2,3,4,5,6,7].rotate(i).last
end
int_map(1)
#=> 1
int_map(7)
#=> 7
int_map(8)
#=> 1
int_map(14)
#=> 7
int_map(15)
#=> 1
PS: May be bit inefficient as the value of i
grows larger, but my tests did not indicate that. May be Ruby implementation is smart and handles multiple rotations in efficient manner.
Upvotes: 2