Figuring out Ruby OOP

I am new to Ruby and to object oriented programming in general. I’m just
trying to write this code this will turn both the first and last names
entered as strings. I realize the irony of this since the names probably
come in as strings but nevertheless here it is:

class Person ## This code crashes
attr_reader :strings
attr_accessor :first
attr_accessor :last

def initialize (firstName,lastName)
self.strings = firstName,lastName
puts strings
end

def strings= (first,last)
@strings = first.to_s,last.to_s
end
end

Thomas = Person.new(“Thomas”,“Wolff”)

Thomas.strings

The code works fine when adapted for just the first name as shown below.
But when I made the changes to it for the last name it crashes.

class Person ## This code runs fine
attr_reader :strings
attr_accessor :first
attr_accessor :last

def initialize (firstName)
self.strings = firstName
puts strings
end

def strings= (first)
@strings = first.to_s
end
end

Thomas = Person.new(“Thomas”)

Thomas.strings

You’re using “=” with two arguments. You can only assign a single value
like that. If you want to send two objects using “=”, then you’ll need
to put them in an Array:

class Person
attr_reader :strings
attr_accessor :first
attr_accessor :last

def initialize (first_and_last_name)
self.strings = first_and_last_name
end

def strings= (first_and_last_name)
@strings = first_and_last_name.map( &:to_s )
end
end

Thomas = Person.new( [ “Thomas”, “Wolff” ] )

Thomas.strings

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs