Ruby Rubinius 正在成为 Ruby 的方言

mizuhashi · January 11, 2017 · Last by rennyallen replied at January 11, 2017 · 2775 hits

https://medium.com/@rubinius/rubinius-takes-the-fun-out-of-ruby-21db64ce87a6

Rubinius 不再自称 Ruby 已经有一段时间了,不过官网上也看不太出他们到底想干什么,刚刚去看了他们的博客,才知道他们打算把 Rubinius 做成 Ruby 的扩展。

例如这篇博文提到,为 Ruby 添加了函数,类型和模式匹配语法:


# Note the block syntax to get around not being
# able to make 'data' a keyword.
data str do
  # ...
end

data int do
  # ...
end

data color do
  # ...
end

# The types above would be defined at the system level
# and available for import as desired.

data MyModel do
  field :name, str
  field :age, int
  field :color, color

  # Return type is specified by annotations.
  type bool
  fun compare_age(a: int, b: int)
    a <=> b
  end
end

文中提到 Object Oriented 面向组件的交互,而 Functional 面向数据操作,OO 和 FP 是对立的,但是可以各取所需。也就是在实际的工程中,应该依据不同的需求选用不同的范式,而不是分成两个派系相互对立。

而作者本人花了八年尝试说服 Ruby 团队接受这些新的设计,依旧没有结果,只好自己来做了这个"additions to Ruby"。

Rubinius 还设计了一个 defm 关键字,可以用来简化 case when:

class Array
  defm [](index)
    # return element at index or nil
  end

  defm [](index, num)
    # return num elements starting at index
  end

  defm [](index: Integer())
    # convert index to an Integer if it's not already
  end

  defm [](range: Range())
    # convert range to a Range if it's not already
  end
end

这个大概就是 [] 的实际定义,index: Integer() 意味着匹配可以被转换为 Integer 的对象。

其实做方言还是不错的,只能希望未来和 Ruby 本身不会有太多冲突,因为 Ruby 目前没有靠谱的 LLVM 前端,如果 Rubinius 不做了,wasm 平台可能就看不到 Ruby 的身影了。

我个人认为模式匹配不是真的那么重要,只是些锦上添花的东西,其实用 dsl 写也没差....Ruby 倒是挺需要一个 import/export,来解决常量作用域的问题..

Over time, Rubinius has changed from using C to using C++, changed the way primitives are implemented, rewritten the bytecode compiler, changed the bytecode interpreter execution model from stackless to using the C stack, changed the way exceptions are handled, added a custom JIT compiler, and replaced that with an LLVM-based one–just to name a few things.

感觉 Rubinius 一直在努力改变,希望最终能成为一门地道的方言,与 Ruby 能够互补,没有冲突各有用途~

You need to Sign in before reply, if you don't have an account, please Sign up first.