argius note

プログラミング関連

Enumerable使いこなしたい

Rubyリファレンスによると、Enumerableは「繰り返しを行なうクラスのための Mix-in。」とある。Arrayクラスなんかが代表的だが、Enumerableのメソッドはたくさんあって覚えるのがたいへんそう。実際、まだいくつか良く分からないものがある。
よく使うのは、このくらい。

a = %w[bright cool dusty active]

# each_with_index
a.sort.each_with_index do |item, index|
  print "[#", index, " : ", item, "]"
end #=> [#0 : active][#1 : bright][#2 : cool][#3 : dusty]

# grep
p a.sort.grep(/i/) #=> ["active", "bright"]

# inject
i = a.inject(0) do |total, item|
  total += item.length
end
p i #=> 21

# map
m = a.map do |item|
  item.reverse
end
p m #=> ["thgirb", "looc", "ytsud", "evitca"]

ほかにもzipとか得体の知れないのがある。
で、例によってPerl版。grepやmapはPerl由来なんでしょうか。

# not strict

@a = qw| bright cool dusty active |;

# (inspect)
sub dump_array { printf "[%s]", join ",", map { "\"$_\"" } @_ }

# (each_with_index)
for (0..$#a) {
  printf"[#%d : %s]", $_, $a[$_];
}

# grep
dump_array grep { /i/ } @a;

# (inject)
$total = 0;
for (@a) {
  $total += length;
}
print $total;

# map
dump_array map { join "", reverse split // } @a;