0

I've attempted to solve this HackerRank Sparse Arrays problem with Ruby.

I wanted to use #tally on the string_list array in order to create a hash of keys and their occurrence count. I have checked this works and prints to my console correctly:

string_list = ['ab', 'ab', 'abc']
string_count = string_list.tally

p string_count: {"ab"=>2, "abc"=>1}

My code is giving me the expected result of an array of integers locally, but when I submit my code to HackerRank it seems to throw a NoMethodError at the use of #tally.

Here is the error below:

Solution.rb:16:in `matchingStrings': undefined method `tally' for ["aba", "baba", "aba", "xzxb"]:Array (NoMethodError)
    from Solution.rb:45:in `<main>'

Could anyone shed some light on why this is throwing an error?

Here is my full code solution, and the terminal output.

def matching_strings(string_list, queries)
  string_count = string_list.tally

  queries.map do |query|
    string_count[query].nil? ? string_count[query] = 0 : string_count[query]
  end
end

string_list = ['ab', 'ab', 'abc']
queries = ['ab', 'abc', 'bc']

p matching_strings(string_list, queries) : [2, 1, 0]

Thanks!

1
  • Nine times out of ten such an error message indicates a mismatch of Ruby versions, the mismatch here identified by @Sebastian below. Commented Mar 16, 2023 at 18:39

1 Answer 1

3

HackerRank uses Ruby 2.6.4. Enumerable#tally was added in Ruby 2.7.0.

You can always check it by printing the value of RUBY_VERSION.

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

2 Comments

Ah, that's simple enough, thank you. I'm using 3.1.2...
I am surprised to learn that Hackerrank uses a version of Ruby that reached end-of-life a year ago.

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.