Skip to content

suggest to use a different example rather then format method #22

Description

@rainchen

the original demo code in README is:

The Date#format Method
class Date
  def format( spec ) self.strftime( spec.to_strftime ); end
end
The new Date#format method formats the date like the passed in example:

date = Date.today   ## test run on 2020-02-09

p date.format( 'January 02, 2006' )         #=> "February 09, 2020"

but the 'format' method is a built in stdlib private istance method of Date:

↪  irb                                                                                                                                                Fri Feb 21 12:03:54 CST 2020
irb 0.9.6(09/06/30) for ruby-2.5.1 [ x86_64-darwin16 ]
using config {:auto_completion=>"on", :auto_indent=>"on", :prompt_mode=>:DEFAULT, :use_bond=>"off"}, type "conf" to display configuration, type "exit" to quit current session
current context: main(Object)#70113110176120
irb(main):001:0> require 'date'
=> true
irb(main):002:0> date = Date.today
=> #<Date: 2020-02-21 ((2458901j,0s,0n),+0s,2299161j)>
irb(main):003:0> date.format
Traceback (most recent call last):
        2: from /Users/rain/.rvm/rubies/ruby-2.5.1/bin/irb:11:in `<main>'
        1: from (irb):3
NoMethodError (private method `format' called for #<Date: 2020-02-21 ((2458901j,0s,0n),+0s,2299161j)>)
irb(main):004:0>

It's not a good idea to override the stdlib method.

Suggest to use a new method such as "format_as":

class Date
  def format_as( spec ) self.strftime( spec.to_strftime ); end
end

date = Date.today   ## test run on 2020-02-09

p date.format_as( 'January 02, 2006' )         #=> "February 09, 2020"

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ideaideas to investigate and think about - why? why not?

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions