Skip to content

Instantly share code, notes, and snippets.

@kotp
Created June 18, 2010 06:10
Show Gist options
  • Save kotp/443312 to your computer and use it in GitHub Desktop.
Save kotp/443312 to your computer and use it in GitHub Desktop.
class Month_Sampler
Months = { 'Jan' => "January", 'Feb' => "February", 'Mar' => "March", 'Apr' => "April",
'May' => "May", 'Jun' => "June", 'Jul' => "July", 'Aug' => "August",
'Sep' => "September", 'Oct' => "October", 'Nov' => "November", 'Dec' => "December"
}
# assign abbreviated and full month names depending on what is provided.
# Because this is a sample short script, I simply fail if wrong input.
def initialize month
fail("Incorrect Month representation (as a string)") unless
Months.has_value?(month) ?
(@full = month ; @abbr = Months.key @full ) :
(@full = Months[month] ; @abbr = Months.key(@full))
end
# This is what we really want to look at...
def to_s
@abbr
end
# to_str means more string like than to_s
def to_str
@full
end
end
sample_month_1 = Month_Sampler.new "Jan"
sample_month_2 = Month_Sampler.new "October"
sample_month_3 = Month_Sampler.new "Sep"
puts "#{sample_month_1} shows with implicit to_s while << shows with implicit to_str like this: " << sample_month_1
puts "#{sample_month_2} shows with implicit to_s while the + uses implicit to_str like this: " + sample_month_2
puts "This format %s shows implicit to_s" % sample_month_3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment