是否有与 Scala 选项等效的 ruby?
如何在 ruby 中为可选值建模? Scala 有 Option[],这正是我在 ruby 中寻找的。
How do I model an optional value in ruby? Scala has Option[], which is what I'm looking for in ruby.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
标准库中没有等效项。你必须定义你自己的。请参阅本文。
There's no equivalent in the standard library. You have to define your own. See this article.
我不是 Ruby 专家,但我认为没有等效的 Option。由于 Ruby 是面向对象的,所以没有什么可以阻止您编写自己的实现,但它不会像静态类型语言那样有用,在静态类型语言中,编译器强制您对空进行适当的检查选项,这是使用此构造的要点之一。当然还有其他优点,例如可以通过多种方式链接选项值。
I'm not a Ruby expert, but I don't think there is an Option equivalent. As Ruby is object oriented, nothing stops you from writing your own implementation, but it won't be as useful as in a statically typed language, where the compiler forces you to do a proper check for the empty option, which is one of the main points for using this construct. Of course there are other advantages, like the possibility to chain Option values in several ways.
您检查过 Rumonade gem 吗?它为您提供了一个以 scala 为模型的 Option 类。
Have you checked out the Rumonade gem? It gives you an Option class modeled on scala.
nkpart 的 adt 库 下的
下有一个
。还有其他示例 ADT,该库使您可以更轻松地定义自己的 ADT。Maybe
类的示例示例/common_adts.rbThere is an example of a
Maybe
class in nkpart's adt library underexamples/common_adts.rb
. There are also other example ADTs and the library makes it easier to define your own.我刚刚推送了一个名为 nil_be_gone 的 gem,它为您提供了一个可以用来包装对象的Optional。它实现method_missing来检查Optional的值是否为nil,如果是,则简单地返回另一个Optional包装的nil值,否则它调用对象上的方法并再次包装它。
nil_be_gone 将
bind
实现为and_then
,它允许您对Optional类型进行链接操作,它的返回方法从Optional is value中检索值,而单元操作将对象包装在monad 由 self.from_value 定义。I have just pushed a gem called nil_be_gone that gives you an Optional that you can wrap objects with. It implements method_missing to check whether the value of the Optional is nil and if so simply return another Optional wrapped nil value, otherwise it calls the method on the object and wraps it again.
nil_be_gone implements
bind
asand_then
which allows you to chain operations on Optional types, it's return methods which retrieves the value from Optional is value and the unit operation which wraps an object in the monad is defined byself.from_value
.我不知道 Scala,所以我不能断言这就是你的答案:
在 ruby 中,当你调用方法时,你可以为参数定义默认值:
在该示例中,你可以省略 i_am_optionnal,它有一个默认值。
HTH。
I don't know Scala, so I can't assert that's your answer:
In ruby, when you call a method, you can define a default value for a param:
In that example, you can omit i_am_optionnal, which has a default value.
HTH.