K.Sasada's Home Page

Diary - 2017 July

研究日記

文月

_13(Thu)

久々に Ruby っぽいコード書いた。

# warmup
ObjectSpace.count_objects({})

def count type
  h1 = {}; h2 = {}
  # warmup
  ObjectSpace.count_objects(h1)
  yield
  ObjectSpace.count_objects(h2)
  p h2.fetch(type, 0) - h1.fetch(type, 0)
end

def foo k1:100, k2:200
end

count :T_HASH do
  foo(k1: 1, k2: 2)
end

実行結果。

[SCRIPT] t.rb
[DIFF] ruby 1.9.3p489 (2014-01-09 revision 44533) [i386-mswin32_110] (0.1 sec)
======================================================================
t.rb:13: syntax error, unexpected ':', expecting ';' or '\n'
def foo k1:100, k2:200
           ^
t.rb:13: warning: possibly useless use of a literal in void context
======================================================================
[DIFF] ruby 2.0.0p647 (2015-08-18 revision 51630) [x64-mswin64_110] (0.1 sec)
======================================================================
2
======================================================================
[SAME] ruby 2.1.8p412 (2015-10-29 revision 52362) [x64-mswin64_110] (0.1 sec)
[DIFF] ruby 2.2.7p418 (2017-01-04 revision 53222) [x64-mswin64_110] (0.2 sec)
======================================================================
0
======================================================================
[SAME] ruby 2.3.3p255 (2017-03-20 revision 56259) [x64-mswin64_110] (0.2 sec)
[SAME] ruby 2.4.1p111 (2017-03-22) [x64-mswin64_110] (0.1 sec)
[SAME] ruby 2.5.0dev (2017-06-22 trunk 59112) [x64-mswin64_110] (0.1 sec)
[TOTAL] 3 results (0.2 sec)

Ruby 2.2 から、keyword 引数でうけると Hash object を作らないよ、という話。

なんか、何十回か count メソッドを書いている気がするので、コアに入れたい気もするけど、ニッチするぎよなあ。

Sasada Koichi / ko1 at atdot dot net
$Date: 2003/04/28 10:27:51 $