[LRUG] [Help request] Programmatically inserting user data into js chart
John Cinnamond
jc at panagile.com
Wed Jun 8 10:03:45 PDT 2016
As an aside, `map` returns an enumerator if you don’t give it a block, and enumerators have a `with_index` method. So instead of:
array.each_with_index.map { |value, idx| … }
You can say:
array.map.with_index { |value, idx| … }
This only saves you 5 characters, but I think it makes the intent slightly clearer.
On Wed, 08 Jun 2016 at 17:57 Tom Stuart
<
mailto:Tom Stuart <tom at codon.com>
> wrote:
On 8 Jun 2016, at 14:32, Jesse Waites <
mailto: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
_______________________________________________
Chat mailing list
mailto:Chat at lists.lrug.org
Archives:
http://lists.lrug.org/pipermail/chat-lrug.org
Manage your subscription:
http://lists.lrug.org/options.cgi/chat-lrug.org
List info:
http://lists.lrug.org/listinfo.cgi/chat-lrug.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20160608/ce8bf8c7/attachment-0002.html>
More information about the Chat
mailing list