0

if

@users = User.all.group_by(&:iso).map{|k,v| [k, v.count]}

returns

 [["GB", 1], ["GI", 3], ["BD", 1]]

Why can't I do this

 @users = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.downcase]}

to get

[["GB", 1, "gb"], ["GI", 3, "gi"], ["BD", 1, "bd"]]

I am getting the error

      undefined method `downcase' for nil:NilClass

How do I get this.

If I do

   @user_json = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.inspect]}

I get

   [["GB", 1, "\"GB\""], ["GI", 3, "\"GI\""], ["BD", 1, "\"BD\""]

and then

  @user_json = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.inspect.downcase]}

 [["GB", 1, "\"gb\""], ["GI", 3, "\"gi\""], ["BD", 1, "\"bd\""]

V. confused

FOR MORE DETAILS - THIS WORKS (but if it is wrong and can't explain why)

I am trying to build a JSON array with the structure:

   [{"code":"GB","value":1,"flag":"gb"},{"code":"GI","value":3,"flag":"gi"},{"code":"BD","value":1,"flag":"bd"}]

My controller code

     def global_chart
          @user_json = User.all.group_by(&:iso).map{|k,v| [k, v.count, k.to_s.downcase]}.map {|c, v | ["code" => c, "value" => v, "flag" => c.to_s.downcase]}.flatten.to_json
          render 'users/charts/global'
    end

This works ( the @user_json variable has the right structure) however I can't explain the behaviour above....

8
  • why you can't? You can Commented Aug 19, 2015 at 15:50
  • I get: undefined method `downcase' for nil:NilClass Commented Aug 19, 2015 at 15:51
  • so one of your 'iso' is empty. try this User.all.group_by(&:iso).map{|k,v| [k, v.count, k.try(:downcase)]} Commented Aug 19, 2015 at 15:52
  • With your code I get: undefined local variable or method `downcase' for #<UsersController:0x007fdab38110b0> Commented Aug 19, 2015 at 15:52
  • what will return k.to_s.downcase? Commented Aug 19, 2015 at 15:55

1 Answer 1

1

Your code

@users = User.all.group_by(&:iso).map{ |k,v| [k, v.count] }

is absolutely valid and its output shows us that you have got only three iso groups. Then

@users = User.all.group_by(&:iso).map{ |k,v| [k, v.count, k.downcase] }

is absolutely valid code as well. But you get an error undefined method 'downcase' for nil:NilClass which tells us that one of iso values is nil. Which is not true from your first example output.

After that, your third snippet

User.all.group_by(&:iso).map{ |k,v| [k, v.count, k.inspect.downcase] }

which is again correct, returns the same output as first one (I mean same sample of iso).

So somewhere in your code is bug. I believe it is close to provided piece of code. You could show whole controller's code to see maybe the problem is on the surface.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.