钉子和方法链 [英] Nils and method chaining

查看:80
本文介绍了钉子和方法链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进入红宝石世界,我可以伸出援手.

I'm just breaking into the ruby world and I could use a helping hand.

假设bnil.

我希望以下代码返回nil而不是"NoMethodError:未定义的方法"

I'd like the following code to return nil instead of a "NoMethodError: undefined method"

a.b.c("d").e

我尝试做的第一件事是重载NilClass的missing_method以简单地返回nil.这是我想要的行为,只是我不想成为这种干扰.

The first thing I tried was to overload NilClass's missing_method to simply return a nil. This is the behaviour I want except I don't want to be this intrusive.

如果我能做这样的事情,我会喜欢的

I'd love it if I could do something like this

SafeNils.a.b.c("d").e

因此,这就像在本地重载NilClass行为的一种干净方法.

So it's like a clean way to locally overload the NilClass's behaviour.

我很想听听一些想法或丰富的资源以进行深入研究.只要它很干净,我也对其他方法持开放态度.

I'd love to hear some ideas or great resources for digging in on this. I'm also quite open to other approaches as long as it's fairly clean.

非常感谢您.

推荐答案

我认为您可以在Rails中找到不错的解决方案,但是该解决方案采用了不同的方法.看一下 try 方法.这是一种干净的方法.

I think you can find a great solution in rails but that solution follows a different approach. Take a look at the try method. It's a clean approach.

这篇关于钉子和方法链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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