dijiri dijiri - 2 months ago 7
Ruby Question

error adding ruby code on a structure

I have a structure defined in 'strct'. Its possible to add some ruby code like the next example?

def strct(i)
{
"mwdata": [
i.times do //incorrect
{
"mwtype": "cell",
"mwsize": [
1,
3
],
"mwdata": [
10,
23,
199
]
}
end //incorrect
]
}
end

Answer

You can multiply arrays by using *, but this will create an Array of references to the same Hash object, changing one, changes all of them. (as @mudasobwa pointed out in the comments)

def strct(i)
  { "mwdata": [ {...} ] * i }
end

It's also possible to use tap:

def strct(i)
  { "mwdata" => [].tap do |array|
      i.times do 
        array << { .... }
      end
    end
  }
end

Or inject:

def strct(i)
  { "mwdata" => 1.upto(i).inject([]) do |array|
      array << { .... }
    end
  }
end 

Note

I understand the reason for this question, as I have often found myself doing something like:

def strct(i)
  result = { "foo" => [] }
  i.times do
    result["foo"] << "Something #{i}"
  end
  result
end

Quick googling gave me this: hash_builder.rb that works like jsonbuilder and can be used to create hash "templates".

Comments