How do I print a multi-dimensional array in ruby?
If you're just looking for debugging output that is easy to read, "p" is useful (it calls inspect() on the array)
p x
[[1, 2, 3], [4, 5, 6]]
Print out 2D array
Suppose:
arr = Array.new(10) { (0..20).to_a.sample(10) }
Thenputs arr.map { |x| x.join(' ') }
1 9 6 15 7 19 18 3 0 12
13 20 18 15 0 3 19 1 14 16
7 16 5 3 12 19 4 9 20 10
6 10 9 1 18 17 7 19 5 15
12 3 8 16 10 5 2 18 20 6
12 9 0 18 2 11 16 8 7 15
8 9 14 19 3 16 6 20 13 17
7 19 16 14 13 6 9 2 3 5
10 17 8 15 11 2 13 14 16 7
14 9 20 17 15 3 4 2 11 19
is not very, er, attractive. For something more pleasing, you could quite easily do something like this:width = arr.flatten.max.to_s.size+2
#=> 4
puts arr.map { |a| a.map { |i| i.to_s.rjust(width) }.join }
1 9 6 15 7 19 18 3 0 12
13 20 18 15 0 3 19 1 14 16
7 16 5 3 12 19 4 9 20 10
6 10 9 1 18 17 7 19 5 15
12 3 8 16 10 5 2 18 20 6
12 9 0 18 2 11 16 8 7 15
8 9 14 19 3 16 6 20 13 17
7 19 16 14 13 6 9 2 3 5
10 17 8 15 11 2 13 14 16 7
14 9 20 17 15 3 4 2 11 19
If you have too many columns to display on the screen you can do this:puts arr.map { |a| a.map { |i| i.to_s.rjust(width) }.join.tinyfy }
1 9 6 15 7 19 18 3 0 12
13 20 18 15 0 3 19 1 14 16
7 16 5 3 12 19 4 9 20 10
6 10 9 1 18 17 7 19 5 15
12 3 8 16 10 5 2 18 20 6
12 9 0 18 2 11 16 8 7 15
8 9 14 19 3 16 6 20 13 17
7 19 16 14 13 6 9 2 3 5
10 17 8 15 11 2 13 14 16 7
14 9 20 17 15 3 4 2 11 19
Ruby - How to access elements in a multi-dimensional array
source.map { |row| row.each_index.select { |i| row[i] == "a" } }
# => [[1, 2], [], [0]]
You can't do it because your logic is mistaken :)
source.each {...}
will returnsource
, doesn't matter what you do inside the block. To return the result, usemap
.source.each.each_index
callseach_index
on the enumerator returned byeach
without block, and that's not a method available on enumerators (you wanteach_index
on arrays).Indeed.
each
with block andeach
without block will do very different things.
Start with source
array. map
with block will process the block for each element (called row
), and return an array of the results. For each row, row.each_index
without block will return an iterator of all indices of the row
array, select
with block on the iterator will return an array that will contain only some of those elements.
Print multidimensional array in rails views
Fix is :
<% @allposts.each do |posts, slots| %>
<% slots.each do |post| %> # <--- see I removed @ symbol
<%= post.Title %>
<% end %>
<% end %>
Your block variable is slots
, and you attempted as @slots
. Which I think is a typo. As there is no such @slots
variable defined, you got nil
, when you wanted to use it. There is a sweet difference between local variable and instance variable. If you don't defined anywhere a local variable say foo
, you will be ended up with undefined local variable or method if you want to use foo
anywhere else.But for instance variable, no error, you will silently get nil
. How do you loop through and print a multidimensional array in a Rails view?
There's no reason you can't use a loop within your view, and that's exactly the way you'd want to do it:
<% @groups.each do |group| %>
<!-- Render stuff -->
<% group.groups.each do |child| %>
<!-- Render child stuff -->
<% end %>
<% end %>
It may be a lot easier to manage if you do this using partials instead:# view.html.erb
<% render partial: 'group', collection: @groups, as: :group %>
# _group.html.erb
<!-- Render stuff -->
<% render partial: 'first_child', collection: group.groups, as: :group %>
Check out the Rendering Collections section of the Rails guide on Layouts and Rendering for some more info.EDIT: If you need to handle an unknown level of nesting, partials would work here too. You can even track the depth if you want. Say you wanted to display them using nested
ul
elements:# _group.html.erb
<% content_tag :li, class: "depth-#{depth}" do %>
<!-- Any output needed for the group itself -->
<% unless group.group.empty? %>
<ul>
<%= render partial "group", collection: group.groups, as: :group,
locals: { depth: depth+1 } %>
</ul>
<% end %>
<% end %>
# In your view file
<ul>
<% render partial "group", collection: @groups, as: :group,
locals: { depth: 0 } %>
</ul>
Ruby multidimensional array
Strictly speaking it is not possible to create multi dimensional arrays in Ruby. But it is possible to put an array in another array, which is almost the same as a multi dimensional array.
This is how you could create a 2D array in Ruby:
a = [[1,2,3], [4,5,6], [7,8,9]]
As stated in the comments, you could also use NArray which is a Ruby numerical array library:
require 'narray'
b = NArray[ [1,2,3], [4,5,6], [7,8,9] ]
Use
a[i][j]
to access the elements of the array. Basically a[i]
returns the 'sub array' stored on position i
of a
and thus a[i][j]
returns element number j
from the array that is stored on position i
. Ruby: how does one print a 2D array?
One could do something like this:
WINNING_ROWS = [[1,2,3],[4,5,6]]
WINNING_ROWS.map { |x| x.inspect }.join("")
Which will get you a string formatted as you requested Is there a simple way to duplicate a multi-dimensional array in Ruby?
Here's the "Ruby-esque" way to handle it:
temp_array = Marshal.load(Marshal.dump(your_array_to_be_cloned))
Related Topics
Why Should @@Class_Variables Be Avoided in Ruby
Indent Multiline String in Erb
Converting Escaped Xml Entities Back into Utf-8
How to Send an Image on The Web in an Xmpp (Jabber) Message
Sorting a Multidimensional Array in Ruby
In Ruby, How to Be Warned of Duplicate Keys in Hashes When Loading a Yaml Document
Modifying Text Inside HTML Nodes - Nokogiri
How to Reverse a Linked List in Ruby
Rails 4 - Devise: Getting Actioncontroller::Unknownformat on Signup
Install Ree-1.8.7 with Rvm on Mountain Lion
How to Avoid Circular Creation of Associated Models in Factory_Girl
Rails: Before Process_Action Callback: Authenticate_User! Has Not Been Defined
How to Send a Keep-Alive Packet Through Websocket in Ruby on Rails
Ruby Readline Fails If Process Started with Arguments
Sorting Hash of Hashes by Value (And Return The Hash, Not an Array)
Puzzled Over Palindromic Product Problem
Why Are Global Methods Allowed to Be Defined Outside of a Class in Ruby
Rails: What's Wrong with This Multiple Join with Conditions on The Associations