[LRUG] [Help request] Programmatically inserting user data into js chart

Tom Stuart tom at codon.com
Wed Jun 8 09:57:43 PDT 2016


On 8 Jun 2016, at 14:32, Jesse Waites <jesse.waites at gmail.com> wrote:
> def make_jsonish(array)
>   array.each_with_index do |num, i|
>     puts "{ key: #{i}, value: #{num}},"
>   end
> end

This looks pretty close to being right, but you want to return a string by joining all the individual lines, not print them out. For example:

def make_jsonish(array)
  array.each_with_index.map { |num, i|
    "{ key: #{i}, value: #{num}},"
  }.join("\n")
end

Less significantly, it would be better to rely on Ruby to turn the resulting data structure (including enclosing square brackets) into JSON for you, so that you’re not responsible for the conversion yourself:

def make_jsonish(array)
  elements = array.each_with_index.map { |num, i|
    { key: i, value: num}
  }
  JSON.pretty_generate(elements)
end

Cheers,
-Tom


More information about the Chat mailing list