0

I have the following function that works just fine

def holiday_hours_for(holiday)
  hours["holiday_hours"][holiday.to_s] if hours["holiday_hours"][holiday.to_s]
end

I am just learning about virtual attributes, and am having some trouble figuring out the setter version of this function. How would I achieve this function...

def holiday_hours_for(holiday)=(hours)
  self.hours["holiday_hours"][holiday.to_s] = hours if hours["holiday_hours"][holiday.to_s]
end

Thanks!

UPDATE: I came up with the following, is this the best way?

  def update_holiday_hours_for(holiday, hours_text)
    self.hours = Hash.new unless hours
    self.hours["holiday_hours"] = Hash.new unless hours["holiday_hours"]
    self.hours["holiday_hours"][holiday.to_s] = hours_text.to_s
  end
Brandon
  • 1,735
  • 2
  • 22
  • 37

1 Answers1

0

the important thing to understand is that setter methods are defined with an "=" sign at the end. like this:

def holiday_hours=(some_parameters)
  # some code
end

this behaves like a setter method for the instance variable @holiday_hours. The method name is "holiday_hours=" and it takes one or more parameters, as required in your app to derive the value for the attribute @holiday_hours. When Ruby sees some code like

holiday.holiday_hours = some_value

it invokes the setter method you've defined. Even though there is some whitespace in this assignment that aren't in the setter method. Ruby interprets this assignment as

holiday.holiday_hours=(some_value)

calling the holiday_hours= method on the holiday object, with argument some_value

It's not clear from your post what the class is in which your example methods dwell, I can guess what the variable hours_text is, but what is the parameter holiday?

Les Nightingill
  • 5,662
  • 1
  • 29
  • 32
  • holiday would be a parameter specifying which holiday. Christmas, New Years, etc – Brandon Nov 03 '12 at 16:19
  • I don't think you are using virtual attributes. You are just setting a hash value. Virtual attributes refers to invoking a setter method for an object where it doesn't actually have the attribute named by the setter. When the method is invoked, it sets an actual attribute. – Les Nightingill Nov 04 '12 at 00:58