I have just started learning ruby and I am unable to find out a solution on printing first_name and last_name for each element of ##people array...
class Person
#have a first_name and last_name attribute with public accessors
attr_accessor :first_name, :last_name
#have a class attribute called `people` that holds an array of objects
##people = []
#have an `initialize` method to initialize each instance
def initialize(x,y)#should take 2 parameters for first_name and last_name
#assign those parameters to instance variables
#first_name = x
#last_name = y
#add the created instance (self) to people class variable
##people.push(self)
end
def print_name
#return a formatted string as `first_name(space)last_name`
# through this method i want to print first_name and last_name
end
end
p1 = Person.new("John", "Smith")
p2 = Person.new("John", "Doe")
p3 = Person.new("Jane", "Smith")
p4 = Person.new("Cool", "Dude")
# Should print out
# => John Smith
# => John Doe
# => Jane Smith
# => Cool Dude
Why would you make the class Person to hold an array of persons?
It's easier if you just wrap your person objects in an array and then iterate over them and invoke their first_name and last_name accessors:
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
#first_name = first_name
#last_name = last_name
end
end
p1 = Person.new("John", "Smith")
p2 = Person.new("John", "Doe")
p3 = Person.new("Jane", "Smith")
p4 = Person.new("Cool", "Dude")
[p1, p2, p3, p4].each { |person| p "#{person.first_name} #{person.last_name}" }
# "John Smith"
# "John Doe"
# "Jane Smith"
# "Cool Dude"
Related
I started learning Ruby today and immediately dove into a question of how to pass an object to another class as its initializer. How do I pass a Name and Address to the initializer of a Person?
Here is my code:
class Name
attr_accessor :first, :last
def initialize (first, last)
#first = first
#last = last
puts "created name"
end
def show ()
puts first, last
end
end
class Address
attr_accessor :street, :city, :state
def initialize (street, city, state)
#street = street
#city = city
#state = state
puts "Created addresss"
end
def show()
puts street, city, state
end
end
class Person
attr_accessor :name, :address
def initialize (name, address)
#name = name
#address = address
end
def show()
puts name
puts addr
puts "created person"
end
end
name = Name.new("Sam", "Spade")
name.show()
addr = Address.new("111 State St", "Albany", "NY")
addr.show()
person = Person.new (name, addr)
person.show()
The diagnostic I get is person.rb:48: syntax error, unexpected ')', expecting '='
...erson = Person.new (name, addr)
It might appear that the creation of the person object is missing a "p", but the code shows the "p" as being present.
I fixed a few bugs in your code.
class Name
attr_accessor :first, :last
def initialize (first, last)
#first = first
#last = last
puts "created name"
end
def show()
puts first, last
end
end
class Address
attr_accessor :street, :city, :state
def initialize (street, city, state)
#street = street
#city = city
#state = state
puts "Created addresss"
end
def show()
puts street, city, state
end
end
class Person
attr_accessor :name, :address
def initialize (name, address)
#name = name
#address = address
end
def show()
name.show
address.show
puts "created person"
end
end
name = Name.new("Sam", "Spade")
name.show()
addr = Address.new("111 State St", "Albany", "NY")
addr.show()
person = Person.new(name, addr)
person.show()
You had an extra space between new and the params Person.new (name, addr)
In the person class the variable is called address not addr
I think instead of putsing the objects in Person#show I'm guessing you wanted to call your show method which puts their attributes.
I think you got confused by the ellipses (...) in the syntax error. It was trying to simplify your code to the erroring part and it just so happened to cut off that p. The real issue is the space after new told the program to call the new method with no params passed in.
I am finishing my coursework, a simple library system.
I am facing a problem like below:
book.rb
class Book
attr_accessor :title, :author, :language, :classification, :isbn, :book_id, :borrow_status
def initialize(title, author, language, classification, isbn, book_id, borrow_status)
#title = title
#author = author
#language = language
#classification = classification
#isbn = isbn
#book_id = book_id
#borrow_status = borrow_status
end
def bookid
#book_id
end
def booklist
#title = #title.split(/ |\_|\-/).map(&:capitalize).join(" ")
#author = #author.split(/ |\_|\-/).map(&:capitalize).join(" ")
#language = #language.capitalize!
#isbn.to_s
#book_id.to_s
{
"Title" => #title,
"Author" => #author,
"Language" => #language,
"Classification" => #classification,
"ISBN" => #isbn,
"Book ID" => #book_id,
"Status" => #borrow_status,
}
end
end
user.rb
require_relative 'book.rb'
class User
attr_accessor :name, :address, :gender, :age, :id, :borrow
def initialize(name, address, gender, age, id, borrow)
#name = name
#address = address
#gender = gender
#age = age
#id = id
#borrow = borrow
end
def userlist
#name = #name.split(/ |\_|\-/).map(&:capitalize).join(" ")
#address = #address.split(/ |\_|\-/).map(&:capitalize).join(" ")
#age.to_s
#id.to_s
if #borrow.nil?
puts "nothing"
elsif
puts #I wish I can put book's name here, if I entered correct #borrow. eg.,for user3's #borrow=4(in top.rb), user3.#borrow=book4.#book_id, then print #name of book4
else
puts "error"
end
the problem is inside user.rb, in if-elsif-else loop, which is
I wish I can put book's name here, if I entered correct #borrow.
eg.,for user3's #borrow=4(in top.rb), user3.#borrow=book4.#book_id,
then print #name of book4
any solution?
#user.rb
require_relative 'book.rb'
class User
attr_accessor :name, :address, :gender, :age, :id, :borrow
def initialize(name, address, gender, age, id, borrow)
#name = name
#address = address
#gender = gender
#age = age
#id = id
#borrow = borrow
end
def userlist
#name = #name.split(/ |\_|\-/).map(&:capitalize).join(" ")
#address = #address.split(/ |\_|\-/).map(&:capitalize).join(" ")
#age.to_s
#id.to_s
if borrow.nil?
puts "nothing"
elsif borrow
puts borrow.title
else
puts "error"
end
end
end
#book = Book.new('Book1', 'Auth1', 'EN', 'fiction', 'isb123', 1, 'borrowed')
#user = User.new('Mr Foo', '123 st', 'male', 23, 123, nil)
#user.borrow=#book
#user.userlist
#=>Book1
But you might instead want to send an array of books, then you'll need to modify your method to handle array
def userlist
#name = #name.split(/ |\_|\-/).map(&:capitalize).join(" ")
#address = #address.split(/ |\_|\-/).map(&:capitalize).join(" ")
#age.to_s
#id.to_s
if borrow.nil?
puts "nothing"
elsif borrow.length > 0 # checks if anythint in the array
borrow.each{ |b| puts b.title }
else
puts "error"
end
end
How can i add all created objects in self.persons ?
class Person
attr_accessor :name, :last_name, :age
def initialize(name, last_name, age = "no_age")
##persons = []
#name = name
#last_name = last_name
#age = age
add(#name, #last_name, #age)
end
def self.persons
##persons
end
private
def add(name, last_name, age)
##persons << [name, last_name, age]
end
end
person1 = Person.new("name1", "lastname1", 12)
person2 = Person.new("name2", "lastname2", 16)
p Person.persons # => [["name2", "lastname2", 16]]
You can use "conditional assignment operator" to check if array is nil.
def initialize(name, last_name, age = "no_age")
##persons ||= []
#name = name
#last_name = last_name
#age = age
add(#name, #last_name, #age)
end
I am looking at this code:
class Student
attr_accessor :first_name, :last_name, :age
def initialize(first, last, age)
#first_name = first
#last_name = last
#age = age
end
def birthday
#age += 1
end
end
class ViewStudent
def initialize(student)
#student = student
end
def do_something
puts "Student name: #{#student.first_name} #{#student.last_name}"
end
end
class UpdateStudent
def initialize(student)
#student = student
end
def do_something
puts "What is the student's first name?"
#student.first_name = gets.chomp
puts "What is the student's last name?"
#student.last_name = gets.chomp
puts "Updated student: #{#student.first_name} #{#student.last_name}"
end
end
choices = [ViewStudent, UpdateStudent]
student = Student.new("John", "Doe", 18)
puts "Select 1 to view student or 2 to update student."
selection = gets.chomp.to_i
obj = choices[selection - 1]
obj = obj.new(student)
obj.do_something
In the last five lines, I understand that selection = gets.chomp.to_i converts the selection options to integers, but how does that work in tandem with obj = choices[selection - 1]?
I'm also not sure what obj = obj.new(student) and obj.do_something do. It looks like a local variable is being set to create a new object with student as the argument. However, obj isn't a class or method to call on?
I can also gather that obj.do_something calls the methods defined for both ViewStudent and UpdateStudent given the selection.
I saw this, but it doesn't answer my question.
obj = choices[selection - 1] just select ViewStudent if 1 and UpdateStudent if 2 from your array by index (choices[0] or choices[1]).
Then you creating an instance of selected class (ViewStudent.new or UpdateStudent.new) and call do_something method on this instance, because this methos difined in both classes:
obj = choices[selection - 1] # obj is ViewStudent or UpdateStudent class
obj = obj.new(student) # obj is ViewStudent or UpdateStudent instance
obj.do_something # call `do something` method on instance
modify this code to create search by first name using user input output must show age and title
# A simple Employee class
class Employee
attr_reader :first_name, :last_name, :title, :age
def initialize(fname, lname, title, age)
#first_name = fname
#last_name = lname
#title = title
#age = age
end
# A string representation of the Employee object
def to_s
"#{first_name} #{last_name}, #{title}, #{age}"
end
end
# The collection class for Employee objects
class Employees
include Enumerable
def initialize
#employees = []
end
# Add Employee objects to the collection
def <<(employee)
#employees << employee
end
# Method mandated by the Enumerable module
def each
#employees.each { |e| yield(e) }
end
end
employees = Employees.new
employees << Employee.new('Anita', 'Baker', 'President', 48)
employees << Employee.new('Frank', 'Gifford', 'Director', 58)
employees << Employee.new('Barbara', 'Eden', 'Secretary', 34)
employees << Employee.new('George', 'Clooney', 'Project Manager', 37)
employees << Employee.new('Emily', 'Davies', 'Programmer', 28)
employees << Employee.new('David', 'Faber', 'Programmer', 55)
employees << Employee.new('Cindy', 'Adams', 'Programmer', 33)
employees << Employee.new('Helen', 'Hamilton', 'Business Analyst', 42)
You have already done all the necessary work by implementing Enumerable interface. Just accept user input and call the Enumerable#find method:
fname = gets.chomp
e = employees.find {|i| i.first_name == fname}