Reputation: 49
I am having trouble understand options with 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)
which gives me an error of
`[]': no implicit conversion of Symbol into Integer (TypeError)
I am not sure what to do to solve this.
Upvotes: 0
Views: 51
Reputation: 33420
opts
means you can pass an "unlimited" number of arguments when calling the function, but all of them should be named, as you can see in the method's body:
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
...
It's assigning the value of the parameter str within the opt one, min_chunk_size, and so on. But in the case of str, this is the only one that doesn't have a "default" value, but even so, this way max_chunk_size
depends on this, when that value as argument isn't provided (since the str.length - 1 assignment).
For making use most_frequent_kmers
you need to provided a String object, as the str argument (really I think it should be a String, as per the name - str). So this way the logic inside is able to keep working, all other local variables in it have default values if they're not provided.
If you want to pass str
as argument, you can just do most_frequent_kmers(str: 'Some String')
, if you don't then it'll return a NoMethodError
, since opt[:str]
will be nil
, and the "fallback" value for when that happens will try to invoke the length
method on nil
.
And tl;dr;, since you're just passing an Integer as argument, Ruby tries to invoke []
on the opts argument, raising the TypeError for trying an implicit conversion since Integer#[]
expects to receive an Integer as argument, and you're passing a symbol.
Upvotes: 1
Reputation: 1892
you should pass instead to most_frequent_kmers
a hash like that:
# depends on the ruby version you are using
# {str: "hey"} and {:str => "hey"} work also
most_frequent_kmers(str: "hey")
Upvotes: 1