Tuesday, February 13, 2018

ruby - Trouble when using match on an array

What i'm trying to do is create a method that can be given an array as an argument. The array should have some numbers in it. The method will return the number of times the array includes each number inside of it. I understand that there are probably many ways to do this, but I'd appreciate it if folks could help me understand why my way is not working rather than just advising me to do something completely different.



So I start by trying this method out




def score (dice)
dice.each do |die|
x = /(die)/.match(dice.to_s).length
end
x
end


and calling it with score ([5])expecting to get an output of 1. However, I get




NoMethodError: undefined method `length' for nil:NilClass
from t2.rb:22:in `block in score'
from t2.rb:21:in `each'
from t2.rb:21:in `score'
from (irb):2
from /home/macs/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `
'


I have also tried changing the match statement slightly (getting rid of the to_s) so it is




 def score (dice)
dice.each do |die|
x = /(die)/.match(dice).length
end
x
end


and calling it with score ([5]) I get




TypeError: no implicit conversion of Array into String
from t2.rb:22:in `match'
from t2.rb:22:in `block in score'
from t2.rb:21:in `each'
from t2.rb:21:in `score'
from (irb):2
from /home/macs/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `
'



Really not sure how I'm supposed to accomplish this matching.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...