Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Ruby2.0新規要素 | lines、chars、bytes、codepointsの戻り値のデータ型変更

概要

lines、chars、bytes、codepointsの戻り値のデータ型変更

詳細

lines、chars、bytes、codepointsはRuby1.9ではEnumeratorを返却していたが、
Ruby2ではArrayを返却するようになった。

そのためRuby1.9までは

print "hoge".chars.to_a.last

のように書いていた部分が

print "hoge".chars.last

のみで書けるようになった。

サンプルコード
# encoding: utf-8
require 'prime'
require 'test_toolbox'

str =<<EOS
aB1
aB2
aB3
EOS

puts str
dp_line __LINE__

%i{lines chars bytes codepoints}.each do |m|
  print "#{m}:#{str.send m}"
  puts
end
出力
aB1
aB2
aB3
--------------------|filename=|line=12|--------------------
lines:["aB1\n", "aB2\n", "aB3\n"]
chars:["a", "B", "1", "\n", "a", "B", "2", "\n", "a", "B", "3", "\n"]
bytes:[97, 66, 49, 10, 97, 66, 50, 10, 97, 66, 51, 10]
codepoints:[97, 66, 49, 10, 97, 66, 50, 10, 97, 66, 51, 10]