当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby DidYouMean模块用法及代码示例


本文简要介绍ruby语言中 DidYouMean模块 的用法。

DidYouMean gem 添加了在出现错误时建议可能的方法/类名称的函数,例如 NameErrorNoMethodError 。在 Ruby 2.3 或更高版本中,它会在启动时自动激活。

@例子

methosd
# => NameError: undefined local variable or method `methosd' for main:Object
#   Did you mean?  methods
#                  method

OBject
# => NameError: uninitialized constant OBject
#    Did you mean?  Object

@full_name = "Yuki Nishijima"
first_name, last_name = full_name.split(" ")
# => NameError: undefined local variable or method `full_name' for main:Object
#    Did you mean?  @full_name

@@full_name = "Yuki Nishijima"
@@full_anme
# => NameError: uninitialized class variable @@full_anme in Object
#    Did you mean?  @@full_name

full_name = "Yuki Nishijima"
full_name.starts_with?("Y")
# => NoMethodError: undefined method `starts_with?' for "Yuki Nishijima":String
#    Did you mean?  start_with?

hash = {foo: 1, bar: 2, baz: 3}
hash.fetch(:fooo)
# => KeyError: key not found: :fooo
#    Did you mean?  :foo

禁用did_you_mean

有时,您可能希望禁用 did_you_mean gem,例如调试错误对象本身的问题。您可以通过在 ruby 命令中指定 --disable-did_you_mean 选项来完全禁用它:

$ ruby --disable-did_you_mean -e "1.zeor?"
-e:1:in `<main>': undefined method `zeor?' for 1:Integer (NameError)

当您无法直接访问 ruby 命令(例如 +rails console+、irb )时,您可以使用 RUBYOPT 环境变量应用选项:

$ RUBYOPT='--disable-did_you_mean' irb
irb:0> 1.zeor?
# => NoMethodError (undefined method `zeor?' for 1:Integer)

获取原始错误消息

有时,您不想完全禁用 gem,但需要在没有建议的情况下获取原始错误消息(例如测试)。在这种情况下,您可以对错误对象使用 #original_message 方法:

no_method_error = begin
                    1.zeor?
                  rescue NoMethodError => error
                    error
                  end

no_method_error.message
# => NoMethodError (undefined method `zeor?' for 1:Integer)
#    Did you mean?  zero?

no_method_error.original_message
# => NoMethodError (undefined method `zeor?' for 1:Integer)

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 DidYouMean模块。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。