本文介绍了等效于 .try() 用于哈希以避免“未定义的方法";零错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 中,如果值不存在,我们可以执行以下操作以避免错误:

In Rails we can do the following in case a value doesn't exist to avoid an error:

@myvar = @comment.try(:body)

当我深入研究散列并且不想得到错误时,等价物是什么?

What is the equivalent when I'm digging deep into a hash and don't want to get an error?

@myvar = session[:comments][@comment.id]["temp_value"] 
# [:comments] may or may not exist here

在上述情况下,session[:comments]try[@comment.id] 不起作用.会怎样?

In the above case, session[:comments]try[@comment.id] doesn't work. What would?

推荐答案

你忘记在 try 之前放一个 .:

You forgot to put a . before the try:

@myvar = session[:comments].try(:[], @comment.id)

因为 [] 是您执行 [@comment.id] 时的方法名称.

since [] is the name of the method when you do [@comment.id].

这篇关于等效于 .try() 用于哈希以避免“未定义的方法";零错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 11:56