Ruby: adding a new element to each array in an array, such that the new element is the downcased version of an existing element -


if

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

returns

 [["gb", 1], ["gi", 3], ["bd", 1]] 

why can't this

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

to

[["gb", 1, "gb"], ["gi", 3, "gi"], ["bd", 1, "bd"]] 

i getting error

      undefined method `downcase' nil:nilclass 

how this.

if

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

i

   [["gb", 1, "\"gb\""], ["gi", 3, "\"gi\""], ["bd", 1, "\"bd\""] 

and

  @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 - works (but if wrong , can't explain why)

i trying build json array 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 ( @user_json variable has right structure) can't explain behaviour above....

your code

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

is absolutely valid , output shows have got 3 iso groups. then

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

is absolutely valid code well. error undefined method 'downcase' nil:nilclass tells 1 of iso values nil. not true first example output.

after that, third snippet

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

which again correct, returns same output first 1 (i mean same sample of iso).

so somewhere in code bug. believe close provided piece of code. show whole controller's code see maybe problem on surface.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -