首页 > 解决方案 > Ruby - 参数中的选项

问题描述

我无法理解 ruby​​ 的选项。

def most_frequent_kmers(opt={})
   str            = opt[:str]
   min_chunk_size = opt[:min_chunk_size] || 1
   max_chunk_size = opt[:max_chunk_size] || str.length - 1
   min_occurences = opt[:min_occurences] || 1
   results        = {}
   top_scoring    = {}
end
most_frequent_kmers(1)

这给了我一个错误

 `[]': no implicit conversion of Symbol into Integer (TypeError)

我不知道该怎么做才能解决这个问题。

标签: ruby

解决方案


opts意味着您可以在调用函数时传递“无限”数量的参数,但所有参数都应该命名,正如您在方法体中看到的那样:

str            = opt[:str]
min_chunk_size = opt[:min_chunk_size] || 1
max_chunk_size = opt[:max_chunk_size] || str.length - 1
min_occurences = opt[:min_occurences] || 1
...

它在选项一、min_chunk_size 等中分配参数 str 的值。但是在 str 的情况下,这是唯一没有“默认”值的,但即便如此,这种方式max_chunk_size取决于这个,当没有提供该值作为参数时(因为 str.length - 1任务)。

为了使用most_frequent_kmers,您需要提供一个字符串对象,作为 str 参数(我真的认为它应该是一个字符串,根据名称 - str)。因此,这样内部的逻辑能够继续工作,如果没有提供,其中的所有其他局部变量都具有默认值。

如果你想str作为参数传递,你可以这样做most_frequent_kmers(str: 'Some String'),如果你不这样做,那么它会返回 a NoMethodError,因为opt[:str]will be nil,并且发生这种情况时的“后备”值将尝试调用lengthon 方法nil

并且 tl;dr;,因为你只是传递一个 Integer 作为参数,Ruby 尝试调用[]opts 参数,引发 TypeError 尝试隐式转换,因为Integer#[]期望接收一个 Integer 作为参数,并且你传递一个符号.


推荐阅读