![](/img/trans.png)
[英]Is it possible to refer to a parameter passed to a method within the passed block in ruby?
[英]Ruby - Option within parameter
我在理解紅寶石的選擇時遇到麻煩。
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)
我不確定該怎么做。
您應該改為將hash傳遞給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來說,這是唯一一個沒有“默認”值的值,但是即使這樣,當未提供該值作為參數時, max_chunk_size
依賴於此(因為str.length- 1個作業)。
為了使用most_frequent_kmers
您需要提供一個String對象作為str參數(確實,我認為它應該是一個String,按名稱-str)。 因此,通過這種方式,內部邏輯可以繼續工作,如果未提供其他所有局部變量,則它們都具有默認值。
如果要將str
作為參數傳遞,則可以執行most_frequent_kmers(str: 'Some String')
,否則,它將返回NoMethodError
,因為opt[:str]
將為nil
,並且“ fallback “發生時的值將嘗試在nil
上調用length
方法。
還有tl; dr ;,因為您只是傳遞一個Integer作為參數,所以Ruby會嘗試在opts參數上調用[]
,從而引發TypeError嘗試隱式轉換,因為Integer#[]
希望接收一個Integer作為參數,並且您正在傳遞符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.