Ask Your Question
1

What is the method for generating a table using Ruby?

asked 2023-05-23 10:49:25 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-23 11:18:02 +0000

nofretete gravatar image

To generate a table using Ruby, you can use the built-in Ruby method called "puts" to print out the elements of the table in a formatted manner. Here is an example code snippet:

table = [
  ["Name", "Age", "Gender"],
  ["John", 23, "Male"],
  ["Jane", 26, "Female"],
  ["Bob", 35, "Male"]
]

table.each do |row|
  row.each do |column|
    print column.to_s.ljust(10)
  end
  puts ""
end

In this example, we first define the table as an array of arrays, with each inner array being a row in the table. We then use a nested loop to iterate through each element in the table and print it out using the print method. We use the ljust method to left-align each column and ensure that they are all the same width. Finally, we use the puts method to print out each row on a new line.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-23 10:49:25 +0000

Seen: 17 times

Last updated: May 23 '23