Gopal Gopal - 4 months ago 7
Ruby Question

Need to new create array in the name of the first element of the array

I have an array

a=["ncd",0.1,0.2,0.3.0.4]


Now, Can I create an array in the name of ncd without declaring the variable, for an example, another array has to be created in the name of ncd like

ncd=[0.1,0.2,0.3.0.4]


but I wouldn't do this statically as shown above, I need to pop up the element from the array and need to create the array,

For an example, I need to create the array using a[0], Is this possible in Ruby?

Answer

I recommend you to have a hash

a = { "ncd" => [0.1,0.2,0.3.0.4] }

Or if you have some array of arrays like this

a = [['ncd1', 0.1,0.2,0.3,0.4], ['ncd2', 0.1,0.2,0.3,0.4]]

you can use some method to get dynamic values

def dynamic(ar)
  ar.each_with_object({}) do |el, hash|
    hash[el.first] = el[1..-1]
  end
end

dynamic a
#=> {"ncd1"=>[0.1, 0.2, 0.3, 0.4], "ncd2"=>[0.1, 0.2, 0.3, 0.4]}

And then

dynamic(a)['ncd1']
#=> [0.1, 0.2, 0.3, 0.4]

But this looks like some kind of ugly syntax in ruby.

UPDATE

Maybe it would be less ugly to pass key as second parameter, i.e.

def dynamic(ar, key)
  ar.each_with_object({}) do |el, hash|
    hash[el.first] = el[1..-1]
  end[key]
end

dynamic a, 'ncd1'

It is up to you to decide.

Comments