0
votes

I have some problem. I have many strings with keys and their belongings, keys are always the same. String looks like "key1=value1;key2=value2..." . So I made global Hash with arrays as values and want to store all data from strings into that hash so I made function:

<%
$all={}
for len in (0..$authors.length-1)
   $all[$authors[len]] = Array.new   #authors are defined and filled earlier
end

def add_hash(from)
   the_from = from.to_s.split(";")
   for one in the_from
      splitted = one.split("=")
      for j in (0..$authors.length.to_i-1)
         if($authors[j] == splitted[0])
            $all[$authors[j]] << splitted[1]
         end
      end
   end
end
%>

but it doesn't seem to work, is something wrong in my code? (note: I can only use Ruby on Rails code)

2
Define "doesn't work". You never actually call add_hash, if you were expecting it to do something. Not sure what the point of the initial hash init is, you can set a default hash value in the Hash constructor. Not sure why this is in what appears to be an ERB template, either. - Dave Newton
Yes, the question is badly put. Can you give an example of the expected input and output of all variables? I don't understand what $authors is made of. Also, be aware that variables are not named with $ sign in ruby. You can also use array.each_with_index { |value, index| #your code }. - Wawa Loo

2 Answers

1
votes

Just for lolz)), cause of

note: I can only use Ruby on Rails code

place it in lolo.rb in initializer folder of rails app

require 'singleton'

class Lolo < Hash
  include Singleton

  def initialize
    super([])
  end

  def add src
    src.to_s.split(";").each do |item|
      splitted = item.split("=")
      self[splitted[0]] = splitted[1]
    end
  end
end

in any place call all =Lolo.instance to access hash, and all.add("key1=value1;key2=value2") to add elements, all.keys is authors list

and don't use global vars cause it could cause a lot of problem

0
votes

Using global variable is a bad practice. Still if you want to use there is no problem.

In your code accessing hash variable using key as string is not allowed. So change the key to symbol by using to_sym

      (ie) $all[$authors[len].to_sym] similarly $all[$authors[j].to_sym]

This may work.