Populate an new array from another array of symbols - ruby

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

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.

Related

Are these objects? Why do they look like that when I print them?

this is my first post and I'm quite new to programming/this site, so I apologise in advance if I'm doing something wrong/annoying.
I wanted to find a way to define objects without having to do so for each object. I came up with this
class Number
def initialize(name)
#name = name
end
def description
puts "I'm #{#name} "
end
end
a = ["zero", "one","two", "three", "four"]
for i in (0..5) do
a[i] = Number.new(a[i])
end
a[3].description
I'm hoping someone can tell me what kind of Frankensteins monster I've created?
It seems to work, a[3].description returns "I'm three" but does that mean three/a[3] exists as its own object and not an element of an array?
Furthermore if I try to do:
puts a[3]
I get:
<Context::Number:0x000000009b7fd0 #name="three">, #
To clarify I just want to know whether I have actually managed to create objects here, and why on earth when I try and access elements of my array I get that weird feedback (kind of seems like its accessing memory or something, but that is a little beyond me)
My thanks in advance for anyone who replies to this.
All objects stand on their own, regardless of whether they are contained by/in other objects such as Array instances.
Regarding this:
<Context::Number:0x000000009b7fd0 #name="three">, #
...did you mean you get that when you puts a[3] and not puts a?
Every instance of Object and its subclasses has a to_s method that returns a string representation of the object. Since you did not override that in your Number class, it used the default implementation defined in class Object. It is showing you:
1) the class name (I presume you defined Number in side a class or module named Context)
2) the object id (a unique id in the Ruby runtime)
3) the string representation of its instance variable(s)
Also, regarding this:
a = ["zero", "one","two", "three", "four"]
This is equivalent and easier to type (I use 2 spaces for better readability):
%w(zero one two three four)
Also, as Ilya pointed out, map will simplify your code. I'll go a little further and recommend this to do the array initialization:
a = %w(zero one two three four).map { |s| Number.new(s) }
Yes, you have created objects. It's just how Ruby represents a class as a string.
class MyClass
attr_accessor :one, :two
def initialize(one, two)
#one, #two = one, two
end
end
my_class = MyClass.new(1, 2)
my_class.to_s # #<MyClass:0x007fcacb8c7c68>
my_class.inspect # #<MyClass:0x007fcacb8c7c68 #one=1, #two=2>

Ruby Array#transpose real world example

Does anyone have a real-world example of a situation where Array#transpose would be useful? I'm struggling to relate the functionality to possible applications.
Consider the following example:
class Array
def mean
reduce(:+) / length
end
end
locations = [
[41.311000, -96.138319],
[41.311355, -96.130380],
[41.315319, -96.138319],
[41.316093, -96.129994],
[41.317640, -96.124372],
[41.315964, -96.121883],
[41.313128, -96.121968],
[41.313160, -96.125101],
[41.309775, -96.125316]
]
latitudes, longitudes = locations.transpose
puts latitudes.inspect
# => [41.311, 41.311355, 41.315319, 41.316093, ...
puts longitudes.inspect
# => [-96.138319, -96.13038, -96.138319, -96.129994 ...
weighted_center = [latitudes.mean, longitudes.mean]
puts weighted_center.inspect
# => [41.31371488888889, -96.12840577777779]
transpose can be thought of as the opposite of zip
It might be useful if you had a collection of names. The first element might be a first name and the second element might be a last name.
You might want to get a list of the first names or the last names
names = [["John", "Smith"],["Roger", "Jones"]]
You could get the first names by calling names.transpose.first

method undefined?

I am new to ruby. I tried to do a simple method(with parameter) call.
class MeowEncoder
def method(c)
puts c
end
end
print "please enter the thing you want"
s = gets.chomp()
MeowEncoder.method(s)
It is only passing parameter and prints it out. But the terminal keep giving me errors like
:MeowEncoder.rb:9: undefined method `toBinary' for MeowEncoder:Class (NoMethodError)
what is going on here?
I made some enhancement.
class MeowEncoder
def encode(n)
toBianry(?n)
puts ""
end
def toBinary(n)
if n < 2
print n
else
toBinary(n / 2)
print n % 2
end
end
end
o = MeowEncoder.new
print "please enter the thing you want: "
s = gets.chomp()
s.each_char{|c| o.encode(c)} #this doesn't work
o.toBinary(212) # this works
I made some enhancement here. I try to convert a char to its ASCII value then to its binary form. I can made the single toBinary works. But the Encode method also gave me same error. What happened?
You defined an instance method, but you're trying to call it on a class object. Try this:
MeowEncoder.new.method(s)
Also, method is a bad name for a method. It will cause a name clash.
To expand on Sergio's answer, if you actually wanted the method defined on the class, there are several ways to accomplish that, but the most straightforward is to prepend the method definition with self like so:
def self.method(c)
puts c
end
That will allow you to invoke the method the way you are currently.
The reason this works is, in the context of defining the method, self is set to the MeowEncoder class. It's equivalent to saying:
def MeowEncoder.method(c)
puts c
end
This is actually another valid way to declare class methods, but using self is better practice, as refactoring becomes easier if you ever change the name of your class.
Instead of each_char use each_byte and no need of encode method.
s.each_byte{|c| o.toBinary(c)}
Book (title, author)
Author (pseudonym, first_name, last_name)
Book_catalog => collection of books
methods
add_book(book)
remove_book(book)
​borrow_book(borrower, book) => voeg boek toe aan borrower.books_borrowed
return_book(borrower, book) => verwijder boek uit borrower.books_borrowed
book_available?(book)
search(title) => geeft gevonden book-object terug (anders nil)
Book_borrowing
book (read-only), date_of_borrowing (read-only), date_of_return (read-only)
borrow_book(book_to_borrow) : #date_of_borrowing = systeem-datum+uur
return_book(book_to_return) : #date_of_return = systeem-datum+uur
Borrower
member_nbr, first_name, last_name, books_borrowed = collection of Book_borrowing
has_book_by_title(title) => geeft true of false terug
has_book(book) => geeft true of false terug
Person(first_name, last_name)

What is the proper way to phrase this statement in Ruby?

I'm new at this, and I'm having trouble finding the proper way to phrase this in Ruby. And I don't know if the Ruby API in SketchUp is different. But, thats what I'm trying to use it for.
def self.initialize_job_info
return{
'salesperson' => ' = $pg_settings['salespersons'[['salesperson']['id']]] if ('on' = $pg_settings['salespersons'[['salesperson']['defsales']]])'
This is what I'm basically trying to do:
This part of the code works as it should
def self.initialize_job_info
return{
'salesperson' => ''
It sets an empty form's initial value of job_info['salesperson']'s value to ' ' if no pre-existing value is found.
So, there is a value I want to place in the Hash that is being passed from $pg_settings.
The value I want is, and I hope this make sense, the value of this specific 'id'
$pg_settings['salespersons'] {//which is a list of 'salesperson'
<salesperson> id="561" name="name" phone="phone number" defsales="on" email="email" </salesperson>
if (defsales == "on") then 'salesperson' => 'value="id"'
Does this make sense?
I'm pulling my hair out, so any help you can give on this would be great.
if those names not inside the quotes are variables that you want to get the values from it should probably be:
'salesperson' => " = $pg_settings[#{salespersons}[[#{salesperson}][#{id}]]] if (#{on} = $pg_settings[#{salespersons}[[#{salesperson}][#{defsales}]]])"
but as Geo said, more detail on the actual purpose/intent would help
BTW, that construc tis called string interpolation (http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#Interpolation)
If you want to interpolate the strings, as in include their value in a string, then maybe this examples can help you:
a = "a string"
b = "this is"
c = "#{b} #{a}"
In the example above, c will have the value: this is a string . Also, while interpolating, valid Ruby code is accepted. So, this is ok too:
c = "#{ b.sub("this","") } #{a}"
And in this case, c will have the value is a string . So, if you need to interpolate something, first think about how you would do it using normal code, and then just add #{} around it.
I figured it out.
Here is the working code
def self.initialize_job_info
return{
'salesperson' => self.default,
}
end
def self .default
salespersons = $pg_settings['salespersons']
salespersons.each do |salesperson|
if (salesperson['defsales'] == 'on')
return salesperson['id']
end
end
end
Looks like I was a long way off.......lol

Dynamically Create Arrays in Ruby

Is there a way to dynamically create arrays in Ruby? For example, let's say I wanted to loop through an array of books as input by a user:
books = gets.chomp
The user inputs:
"The Great Gatsby, Crime and Punishment, Dracula, Fahrenheit 451,
Pride and Prejudice, Sense and Sensibility, Slaughterhouse-Five,
The Adventures of Huckleberry Finn"
I turn this into an array:
books_array = books.split(", ")
Now, for each book the user input, I'd like to Ruby to create an array. Pseudo-code to do that:
x = 0
books_array.count.times do
x += 1
puts "Please input weekly sales of #{books_array[x]} separated by a comma."
weekly_sales = gets.chomp.split(",")
end
Obviously this doesn't work. It would just re-define weekly_sales over and over again. Is there a way to achieve what I'm after, and with each loop of the .times method create a new array?
weekly_sales = {}
puts 'Please enter a list of books'
book_list = gets.chomp
books = book_list.split(',')
books.each do |book|
puts "Please input weekly sales of #{book} separated by a comma."
weekly_sales[book] = gets.chomp.split(',')
end
In ruby, there is a concept of a hash, which is a key/value pair. In this case, weekly_sales is the hash, we are using the book name as the key, and the array as the value.
A small change I made to your code is instead of doing books.count.times to define the loop and then dereference array elements with the counter, each is a much nicer way to iterate through a collection.
The "push" command will append items to the end of an array.
Ruby Docs->Array->push
result = "The Great Gatsby, Crime and Punishment, Dracula, Fahrenheit 451,
Pride and Prejudice, Sense and Sensibility, Slaughterhouse-Five,
The Adventures of Huckleberry Finn".split(/,\s*/).map do |b|
puts "Please input weekly sales of #{b} separated by a comma."
gets.chomp.split(',') # .map { |e| e.to_i }
end
p result
Remove the comment if you would like the input strings converted to numbers
One way or another you need a more powerful data structure.
Your post gravitates toward the idea that weekly_sales would be an array paralleling the books array. The drawback of this approach is that you have to maintain the parallelism of these two arrays yourself.
A somewhat better solution is to use the book title as a key to hash of arrays, as several answers have suggested. For example: weekly_sales['Fahrenheit 451'] would hold an array of sales data for that book. This approach hinges on the uniqueness of the book titles and has other drawbacks.
A more robust approach, which you might want to consider, is to bundle together each book's info into one package.
At the simplest end of the spectrum would be a list of hashes. Each book would be a self-contained unit along these lines:
books = [
{
'title' => 'Fahrenheit 451',
'sales' => [1,2,3],
},
{
'title' => 'Slaughterhouse-Five',
'sales' => [123,456],
},
]
puts books[1]['title']
At the other end of the spectrum would be to create a proper Book class.
And an intermediate approach would be to use a Struct (or an OpenStruct), which occupies a middle ground between hashes and full-blown objects. For example:
# Define the attributes that a Book will have.
Book = Struct.new(:title, :weekly_sales)
books = []
# Simulate some user input.
books_raw_input = "Fahrenheit 451,Slaughterhouse-Five\n"
sales_raw_input = ['1,2,3', '44,55,66,77']
books_raw_input.chomp.split(',').each do |t|
ws = sales_raw_input.shift.split(",")
# Create a new Book.
books.push Book.new(t, ws)
end
# Now each book is a handy bundle of information.
books.each do |b|
puts b.title
puts b.weekly_sales.join(', ')
end
Are you happy to end up with an array of arrays? In which this might be useful:
book_sales = books_array.collect do |book|
puts "Please input weekly sales of #{books_array[0]} separated by a comma."
gets.chomp.split(",").collect{ |s| s.to_i }
end
Looking at it, you might prefer a hash, keyed by book. Something like this:
book_sales = books_array.inject({}) do |hash, book|
puts "Please input weekly sales of #{books_array[0]} separated by a comma."
weekly_sales = gets.chomp.split(",").collect{ |s| s.to_i }
hash[book] = weekly_sales
end
This solution assumes that there will never be a duplicate book title. I figure that is pretty safe, yes?
input = "A list of words"
hash = {}
input.split(/\s+/).collect { |word| hash[word] = [] }
# Now do whatever with each entry
hash.each do |word,ary|
ary << ...
end

Resources