Home > Net >  TypeError: no implicit conversion of Fixnum into Hash - Ruby
TypeError: no implicit conversion of Fixnum into Hash - Ruby

Time:04-07

Did I try google?

Yes, I tried stack overflow, google, rubydocs, bunch of websites but there are minimal results to this and it's only ever mentioned indirectly. So yes, I did a lot of searching.

What's working?

I run the following query:

requests = Request.where("customer_id = ? 
 AND request_method != ? 
  AND request_time 
   BETWEEN ? AND ?",
    customer.id, "OPTIONS", start_time, end_time).group('request_time')

As a result I get a bunch of values from the Database which look like this and this is CORRECT:

 #<ActiveRecord::Relation[#<Request id: 171792, request_time: "2022-04-04 14:07:20">,
   #<Request id: 171787, request_time: "2022-04-04 14:06:02">...]

NOTE: I didn't paste all the values because they have a similar structure.

What's the problem?

After running the query I want to pass it to the variable dates_init_hash = {} and merge it whilst counting into data[:requests]:

dates_init_hash = {}
(start_time.to_date..end_time.to_date).each do |date|
  dates_init_hash[date] = 0
end

data[:requests] = dates_init_hash.merge(requests.count)

Unfortunately, I always seem to be getting the error:

ERROR -- : TypeError: no implicit conversion of Fixnum into Hash

Expected

I should be getting a Hash like the following:

{ "2022-03-24"=>2, "2022-03-25"=>1, "2022-03-28"=>3, "2022-03-29"=>11}

What I tried

  1. I tried to convert the results to a hash before passing it over but this gave me the error that the .to_h method doesn't exist
  2. data[:requests] = dates_init_hash.merge({requests: requests.count }) works half-way still causing errors

Questions

  1. Why am I getting a Fixnum and why won't this work? How can I improve this? What would be the right way to solving this? I appreciate any kind of help.

CodePudding user response:

Why is the error happening?

You are getting the error because when you run:

data[:requests] = dates_init_hash.merge(requests.count)

dates_init_hash is a hash, and requests.count is a number. So you are trying to merge a number into a hash, what is not allowed.

How can I fix it?

If what you want is to have the dates_init_hash with a mapping date => number of requests that date, you can do the following:

# initializes dates_init_hash with desired dates
dates_init_hash = {}
(start_time.to_date..end_time.to_date).each do |date|
  dates_init_hash[date.iso8601] = 0
end

# iterates over reuests and add 1 to the date in dates_init_hash for each request in the desired date
requests.each do |request|
  date = Date.parse(request[:request_time]).iso8601
  next if dates_init_hash[date].nil? 

  dates_init_hash[date]  = 1
end

Then, dates_init_hash will be something like

{"2022-04-04"=>1, "2022-04-05"=>0, "2022-04-06"=>1, "2022-04-07"=>0}
  • Related