Ruby 2.5 の変更内容 その1

Rubyは毎年クリスマスにバージョンアップされます。

今年も12/25にRuby 2.5がリリースされました。 https://www.ruby-lang.org/ja/news/2017/12/25/ruby-2-5-0-released/

https://docs.ruby-lang.org/en/trunk/NEWS.html を元に変更内容を調べてみました。

前に書いたのは 2.5.0 preview1 時点のものでしたが、それから結構変わっています。

長くなったので3つにわけてます。


個人的にはブロック内の rescue/else/ensure に begin, end を書かなくてよくなったのが嬉しいです。



言語仕様

トップレベル定数参照

class Foo
end
class Bar
end

# Ruby 2.4
Foo::Bar  #=> Bar

# Ruby 2.5
Foo::Bar  #=> NameError 例外

2.5 の方が自然ですね。

rescue/else/ensure 節

def foo
  begin
     ...
  rescue
     ...
  end
end

これは従来から次のように begin を省略できましたが、

def foo
  ...
rescue
  ...
end

2.5からはdo〜endブロックでも省略できます。

array.each do
  begin
    ...
  rescue
    ...
  end
end

array.each do
  ...
rescue
  ...
end

簡潔に書けて良いです。

文字列内式のRefinement

class A
  def to_s
    "a"
  end
end

module B
  refine A do
    def to_s
      "b"
    end
  end
end

class C
  using B
  def x
    A.new.to_s  #=> "b"
    "#{A.new}"  #=> "b" 2.4 では "a"
  end
end

Unicode バージョン 10.0.0

Ruby 2.4 は 9.0.0

Unicode 9.0.0 と 10.0.0 の違いはわかってませんが…。


その他

バックトレースの順番

標準エラー出力が端末の場合に表示が逆順になります。

# Ruby 2.4
% ruby /tmp/a.rb
/tmp/a.rb:8:in `c': unhandled exception
    from /tmp/a.rb:5:in `b'
    from /tmp/a.rb:2:in `a'
    from /tmp/a.rb:10:in `<main>'
# Ruby 2.5
% ruby /tmp/a.rb
Traceback (most recent call last):
    3: from /tmp/a.rb:10:in `<main>'
    2: from /tmp/a.rb:2:in `a'
    1: from /tmp/a.rb:5:in `b'
/tmp/a.rb:8:in `c': unhandled exception

標準エラー出力が端末でなければ従来通り。

% ruby /tmp/a.rb 2>&1 | cat
/tmp/a.rb:8:in `c': unhandled exception
    from /tmp/a.rb:5:in `b'
    from /tmp/a.rb:2:in `a'
    from /tmp/a.rb:10:in `<main>'

configure で拡張ライブラリを強制

通常は configure 時の環境に応じて使えるライブラリが自動判別されますが、--with-ext オプションで強制することができます。コンパイルできる環境でない場合は make でエラーになります。

% ./configure --with-ext=openssl,+
% make
...
*** Following extensions are not compiled:
openssl:
    Could not be configured. It will not be installed.
    /tmp/ruby-2.5.0-preview1/ext/openssl/extconf.rb:94: OpenSSL library could not be found. You might want to use --with-openssl-dir=<dir> option to specify the prefix where OpenSSL is installed.
    Check ext/openssl/mkmf.log for more details.
*** Fix the problems, then remove these directories and try again if you want.
exts.mk:1853: ターゲット 'note' のレシピで失敗しました
make[1]: *** [note] エラー 1
make[1]: ディレクトリ '/tmp/ruby-2.5.0-preview1' から出ます
uncommon.mk:236: ターゲット 'build-ext' のレシピで失敗しました
make: *** [build-ext] エラー 2

default gem

次のライブラリが default gem になりました。

  • cmath
  • csv
  • date
  • dbm
  • etc
  • fcntl
  • fiddle
  • fileutils
  • gdbm
  • ipaddr
  • scanf
  • sdbm
  • stringio
  • strscan
  • webrick
  • zlib

今までは bigdecimal, io-console, json, openssl, psych, rdoc だけだったので、かなり増えました。

Ruby の標準添付ライブラリを gem 化しようという流れの一環です。

Bundler Gem 標準添付は延期

Ruby 2.5 に入る予定だったのですが、2.5 リリースには間に合わなかったようです。