My attr_writer


#1



class Director
	attr_reader :name, :style
	attr_writer :film_1, :film_2, :film_3 
	def initialize(name, style)
		@name = name 
		@style = style
		@film_list = {}
	end
	
	def director_commands 
		@command_1 = "Action!"
		@command_2 = "Quit on the set!"
		@command_3 = "Break"
		@command_4 = "Cut"
	end
	
	def signature
		print " #{:film_1}, #{:film_2}, #{:film_3} "
		@film_list[:film_1] = 4
		@film_list[:film_2] = 4
		@film_list[:film_3] = 4
		puts @film_list
	end 
	
	def add_movie 
	loop do
	puts "Add a movie this director has finished!"
		movie = gets.chomp
		puts "Would you like to rar "
		end
	end
	end
	
	michael_bay = Director.new("Michael", "Action")
	michael_bay.film_1 = "Transformers"
	michael_bay.film_2 = "transformers2"
	michael_bay.film_3 = "Transformers3"
	puts michael_bay.signature

The question i have here is that when i try to write over the film symbols in the respective instance of the class it doesn't write over the films. Instead it just prints the word films when i use the signature method instead of printing the Transformers movies.


#2

These attributes must be written into the class initialize method in order to be able to set them.


#3

Thank's for your response. Would you mind breaking down initialize for me. Because below i pasted a some syntax of a person who didn't initialize but used writer. Could the fact that he required this to another file be the reason it worked?

class Address
attr_accessor :kind, :street_1, :street_2, :city, :state, :postal_code

def to_s(format = 'short')
address = ''
case format
when 'long'
address += street_1 + "\n"
address += street_2 + "\n" if !street_2.nil?
address += "#{city}, #{state} #{postal_code}"
when 'short'
address += "#{kind}: "
address += street_1
if street_2
address += " " + street_2
end
address += ", #{city}, #{state}, #{postal_code}"
end
address
end
end

home = Address.new
home.kind = "Home"
home.street_1 = "123 Main St."
home.city = "Portland"
home.state = "OR"
home.postal_code = "12345"

puts home.to_s('short')
puts "\n"
puts home.to_s('long')


#4

This is a matter for more reading on accessors.

http://www.rubyist.net/~slagell/ruby/accessors.html

I'm afraid if I attempt to answer this it may be incorrect, incomplete or just plain confusing. Best let the experts weigh in on this.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.