0

The no_repeats method is to check if any of the years in the range have repeating number. I paired it with a no_repeat? method that checks individual years.

def no_repeats(year_start, year_end)
  no_repeat_years = [year_start..year_end].select { |year| no_repeat?(year) }
end

def no_repeat?(year)
  numbers = year.split("")
  numbers.each do |n|
    if numbers.count(n) > 1
      return false
    end
  end

  return true
end

When I try to run the no_repeats, I'm getting the following error:

undefined method `split' for 1980..2000:Range (NoMethodError)

Why is the entire range getting plugged into the helper function?

1 Answer 1

2

On the third line, you have [year_start..year_end]. This is not what you want. What this does is it creates an array containing 1 element: your range. So this becomes equivalent to this:

years = year_start..year_end
value = [years]
value.select do |year|
  year.class # => Range
end

So, instead of [year_start..year_end], you should do (year_start..year_end). Instead of creating an array, this puts precedence on the range, so it will still work as expected (i.e. the #select method will be called on the range instead of year_end).

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you! That makes sense now.
No problem! Don't forget to accept the answer if you're content with it.
Just a last question, does that mean that [0..5] is a range but (0..5) would create an array of the range numbers?
No. [] creates an array, () does nothing. [1, 2, 3] would create an array containing three elements, whereas (1, 2, 3) would error. () is used to manually specify precedence; for example, when doing math, 1 + 2 * 3 would result in 7, but (1 + 2) * 3 would result in 9.
Ok, thank you. I hope this doesn't sound dumb, but I'm trying to understand why: [1, 2, 3].select {|n| n.even?} works but [1..3].select {|n| n.even?} doesn't? Doesn't [1..3] technically create an array?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.