我很难理解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)
我不知道该怎么办才能解决这个问题。
您应该向most_frequent_kmers
传递这样的散列:
# depends on the ruby version you are using
# {str: "hey"} and {:str => "hey"} work also
most_frequent_kmers(str: "hey")
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
...
它在opt-one、min_chunk_size等中分配参数str的值。但在str的情况下,这是唯一没有"默认"值的值,但即使如此,当没有提供该值作为参数时(因为str.length-1赋值(,max_chunk_size
也依赖于此。
为了使用most_frequent_kmers
,您需要提供一个String对象作为str参数(实际上,我认为它应该是一个String,根据名称-str(。因此,通过这种方式,内部的逻辑能够继续工作,其中的所有其他局部变量都有默认值,如果没有提供的话。
如果您想将str
作为参数传递,您可以只执行most_frequent_kmers(str: 'Some String')
,如果不执行,则它将返回NoMethodError
,因为opt[:str]
将是nil
,并且发生这种情况时的"回退"值将尝试调用nil
上的length
方法。
和tl;博士由于您只是传递一个Integer作为参数,Ruby尝试在opts参数上调用[]
,从而引发TypeError以尝试隐式转换,因为Integer#[]
希望接收一个Integr作为参数,而您传递的是一个符号。