Some _Times_ You Just Want _Things_
Working on an AES implementation in ruby, I’ve had many occasion to do:
n.times {|i| some calculations based on i}
I’m sure many of you have used the Integer#times method much to your glee. I’m sure many of you have also had the occasion where you realize that you want those resultant calculations to end up in an array of some sort. At this point you have two options: create an array before hand and << those results in, or change your iterator to (0...n).map {|i| ...}. Both options are severely lacking in taste, IMO. So I came up with a third option. Enter Integer#things.
ary = n.things {|i| ...}
Notice how the syntax here remains consistent with the semantics. Before you wanted to do something n times. Here you want the same, but you want to store the results, you want n results, or n things.
Don’t get me wrong, I love Range and it certainly has it’s place. I would never argue that 26.things { make a letter } is a better approach than ('a'..'z') { just have your letter already }. Like I said, it’s about semantics, do you really want that range or is it more about the number of things? And as we all know deep down, the syntactics should match the semantics wherever possible.
So here is my implementation for Integer#things and I really hope something like this becomes included in future ruby.
class Integer
def things &b
b ||= proc {|i| i}
ary = []
times do |i|
ary << yield(i)
end
ary
end
end
@
Post a comment
Website and email are optional. Email will be displayeduser at example dot com.