ruby 中 groovy 的链式属性是否有等效的空预防? [英] Is there an equivalent null prevention on chained attributes of groovy in ruby?

查看:30
本文介绍了ruby 中 groovy 的链式属性是否有等效的空预防?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常规:

如果有 my_object -> 访问 'name' 并大写

if there`s my_object -> access 'name' and capitalize

my_object?.name?.capitalize()

ruby 使用此功能避免使用 nil 对象访问属性的等效项是什么?

What is the equivalent for ruby to avoid a nil object to access attributes with this facility?

谢谢

推荐答案

这适用于 Rails:

This works in Rails:

my_object.try(:name).try(:capitalize)

如果你想让它在 Ruby 中工作,你必须像这样扩展 Object:

If you want it to work in Ruby you have to extend Object like this:

class Object
  ##
  #   @person ? @person.name : nil
  # vs
  #   @person.try(:name)
  def try(method)
    send method if respond_to? method
  end
end

来源

Rails 中,它是这样实现的:

In Rails it's implemented like this:

class Object
  def try(*a, &b)
    if a.empty? && block_given?
      yield self
    else
      __send__(*a, &b)
    end
  end
end

class NilClass
  def try(*args)
    nil
  end
end

这篇关于ruby 中 groovy 的链式属性是否有等效的空预防?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆