Dominic
Dominic

Reputation: 341

Populate an new array from another array of symbols

I have a question about Ruby arrays but it's kind of hard to describe so I could not find much from reading other questions. Here it is.

Currently I have the following code that works (part of Prawn's table)

Snippet A:

  students = all_students.map do |student|          
      [
      student[:first_name],
      student[:last_name],
      student[:email],
      student[:given_name]
      ]
  end
  pdf.table students

This works fine, but now I'd like to omit some of the columns (e.g. don't show last_name). Say I get an array of column names, let's say pickedColumns:

Snippet B:

  pickedColumns = []
  pickedColumns << :first_name << :email << :given_name  #NOTE: no (:last_name) there!

  students = all_students.map do |student|
      studentCols = pickedColumns.each do |studentCol|
        student[studentCol]
      end
  end
  p.table students

I haven't been able to achieve the effect of snippet A, using the replaced code in snippet B. All I get in snippet B are not the actual values of "student[:first_name]" of just a string "first_name" for each row.

If my description is not 100% clear, please let me know.

Thanks for you help!

Regards

Upvotes: 1

Views: 174

Answers (1)

sepp2k
sepp2k

Reputation: 370102

students = all_students.map do |student|
  studentCols = pickedColumns.each do |studentCol|
    student[studentCol]
  end
end

Make that

students = all_students.map do |student|
  pickedColumns.map do |studentCol|
    student[studentCol]
  end
end

and it will work.

PS: To adhere to ruby's naming convention you should change your variable names to use all lower case and underscores, rather than camelCase.

Upvotes: 3

Related Questions