當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。