💎️

Ruby 4.0.0 の気になる機能を試す

に公開

バージョン確認

RUBY_VERSION   # => "4.0.0"
Ruby::VERSION  # => "4.0.0"

RUBY_* は Ruby::* と書けるようになった。

Ruby::Box

box = Ruby::Box.new
box.eval("Ruby::Box.current")  # => #<Ruby::Box:3,user,optional>
box.eval("X = 5")              # => 5
Pathname("y.rb").write("Y = 6")
box.require("./y")             # => true
box.eval("[X, Y]")             # => [5, 6]
[box::X, box::Y]               # => [5, 6]

いままでグローバルスコープにしかできなかったものを閉じ込めることができる。

rfind

[5, 6, 7].rfind(&:odd?)            # => 7
[5, 6, 7].lfind(&:odd?) rescue $!  # => #<NoMethodError: undefined method 'lfind' for an instance of Array>

後ろから探せる。lfind はない。

前に && が書ける

条件の列を揃えるかつ行を入れ替えることができる書き方をしたいときに、

if true &&
    :a &&
    :b &&
    :c &&
    true
  :OK  # => :OK
end

としていたのが、

if true
  && :a
  && :b
  && :c
  :OK  # => :OK
end

と書けるようになったものの if の中身と条件のインデントが揃っているのがやや気になる。

そういえば DHH が X で絶賛しているのは見た。

implicit_parameters

1.then { binding.implicit_parameters }  # => []

としても出てこないので戸惑ったが、

1.then { v = binding.implicit_parameters; it; v }  # => [:it]
1.then { it; binding.implicit_parameters }         # => [:it]
1.then { _1; binding.implicit_parameters }         # => [:_1]

ブロック内のどこかで参照したら出てくるようだ。

produce

安全のために上限を指定できるようになったのかなと早合点してしまった。実際は上限とかぜんぜん関係なく、

enum = Enumerator.produce(0, size: 3, &:next)

のとき、

enum.size  # => 3

になるというだけであった。

  • enum.to_a が [0, 1, 2] になるわけではない
  • size に関係なく enum.to_a は無限生成になる (固まる)
  • 途中で StopIteration しても size は変わらない

instance_variables_to_inspect

class Foo
  def initialize
    @a = nil
    @b = nil
  end
end
Foo.new  # => #<Foo:0x00000001045a37a0 @a=nil, @b=nil>

となっているときに、

class Foo
  private
  def instance_variables_to_inspect
    [:@a]
  end
end

とすると

Foo.new  # => #<Foo:0x00000001045a2710 @a=nil>

inspect の内容を絞れる。

log1p, expm1

小さな値を直接演算すると精度が落ちるので、

x = 1.0e-16  # => 1.0e-16
x + 1        # => 1.0
Math.log(x + 1)  # => 0.0
Math.exp(x) - 1  # => 0.0

専用の命令を用意したらしい。

Math.log1p(x)  # => 1.0e-16
Math.expm1(x)  # => 1.0e-16
  • log1p → log 1 plus → log(x + 1) のこと
  • expm1 → exp minus 1 → exp(x) - 1 のこと

Ractor::Port

まず Ractor とは何なのかというところから調べてみると、Thread のようなものらしい。

Thread.new { 1 + 2 }.value  # => 3
Ractor.new { 1 + 2 }.value  # => 3

で、Thread でこう書いていたのが、

queue = Queue.new
Thread.new(queue) { |queue| queue << 1 + 2 }
queue.shift  # => 3

Ractor ではこうなる。

port = Ractor::Port.new
Ractor.new(port) { |port| port << 1 + 2 }
port.receive  # => 3

strip

str = "\n x x \n"                                # => "\n x x \n"
str.gsub(/\A\p{Space}*(.*?)\p{Space}*\z/, '\1')  # => "x x"

が、

str.strip("\t\r\n\u3000 ")  # => "x x"

と書けるようになったものの個人的には \p{Space} を使いたい。

str.strip(/\p{Space}+/) rescue $!  # => #<TypeError: no implicit conversion of Regexp into String>

とはいえ、全角スペースがらみのときは ActiveSupport の squish があれば困らないし、

require "active_support/core_ext/string/filters"
str.squish  # => "x x"

前後に絞るなら、

str.remove(/\A\p{Space}+/, /\p{Space}+\z/)  # => "x x"

でいい。

open("|command")

open("|echo xxx", &:read) rescue $!  # => #<Errno::ENOENT: No such file or directory @ rb_sysopen - |echo xxx>
IO.popen("echo xxx", &:read)         # => "xxx\n"

open でコマンドを実行する裏技は禁止になった。

(..5).max(3)

(0..).min(3)  # => [0, 1, 2]
(..5).max(3)  # => [5, 4, 3]

max の方だけ RangeError になっていたのが正しく取れるようになった。

birthtime

Pathname("/").birthtime  # => 2025-04-12 14:16:09 +0900

Linux でも birthtime が使えるようになった。

Pathname

Pathname  # => Pathname

最初から使えるようになって、これがいちばんうれしい。

Discussion