how to MAKE ruby print all appropriate brackets in a 2D array -
i see sorts of advice getting rid of brackets, perform beginning ruby lessons, want see if i'm creating 2-d array correctly.
right i'm limited to
puts my_2d_array[0] puts my_2d_array[1] #etc
but want see
[ [6,6,3] , [7,4,7] , [4,7,4] ]
instead of i'm getting, is
663747474
what's trick? , i'm dealing array - not string...
p array
give output you've asked for:
[[6,6,3] , [7,4,7] , [4,7,4]]
want each row on separate line? use:
array.each {|e| p e}
to get:
[6,6,3] [7,4,7] [4,7,4]
you add method array class:
class array def ppa # 'pretty-print array' self.each {|e| p e} # or 'each {|e| p e}' end end
that wold allow write
array.ppa
and same three-line output. (you use puts
, inspect
instead of p
.) think might use often? put code in file called, say, 'array_print.rb' , add 'require array_print'
beginning of '.rb' code file. each time run program, statements in array_print.rb
executed, making array
method ppr
available you.
let's not stop there! suppose wanted nicely-formatted output three-dimensional arrays, hashes, hashes of arrays, , on. elaborate on approach i've described above, why reinvent wheel? there several excellent ruby gems available take care of of you. 1 popular 1 "awesome print". after having installed gem, need add require 'awesome_print'
in code file. can use ap
method format output. (see rubygems instructions on how install gems. it's easy).
to taste of awesome print does, suppose instead of array above wanted display hash:
hash = {"cat"=>["mice", "birds"], "dog"=>["master",["kids", "moms"]]}
by executing ap hash
, you'd this:
{ "cat" => [ [0] "mice", [1] "birds" ], "dog" => [ [0] "master", [1] [ [0] "kids", [1] "moms" ] ] }
Comments
Post a Comment