|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
> > class Fixnum > attr_accessor :note > end > > 13.note = "a baker's dozen" > 25.note = "5 squared" > > notes = [13, 21, 25].collect { |x| x.note } # ["a baker's dozen", > nil, "5 squared"] > It's really cool. -- Posted via http://www.ruby-forum.com/. |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
[Note: parts of this message were removed to make it a legal post.]
Welcome to Monkey Patching! This is how ActiveResource gives you things like: 4.days.ago "some string".underscore and the like. It's one of the many things that makes Ruby code very fun to write. Jason On Jan 5, 2008 10:07 AM, Barca Junior <wuzhengchun@gmail.com> wrote: > > > > > class Fixnum > > attr_accessor :note > > end > > > > 13.note = "a baker's dozen" > > 25.note = "5 squared" > > > > notes = [13, 21, 25].collect { |x| x.note } # ["a baker's dozen", > > nil, "5 squared"] > > > > > It's really cool. > -- > Posted via http://www.ruby-forum.com/. > > |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
On Jan 5, 2008, at 10:15 AM, Jason Roelofs wrote: > Welcome to Monkey Patching! This is how ActiveResource gives you > things > like: > > 4.days.ago > > "some string".underscore > > and the like. > > It's one of the many things that makes Ruby code very fun to write Actually it is a bit different. Monkey patching is just adding methods to classes. Fixnum and String in your examples. Instance variables on Fixnums (or Symbols or Nil) is different. It is a good example of uniformity in Ruby but I'm hard pressed to think of a nice use case for the feature. Gary Wright |
|
|
|
#4 |
|
Messages: n/a
Hébergeur: |
On Jan 5, 2008 4:32 PM, Gary Wright <gwtmp01@mac.com> wrote:
> Actually it is a bit different. Monkey patching is just adding > methods to classes. Fixnum and String in your examples. > > Instance variables on Fixnums (or Symbols or Nil) is different. > It is a good example of uniformity in Ruby but I'm hard pressed > to think of a nice use case for the feature. > > Gary Wright You can use it to cache the result of method calls. class Fixnum def factorial @factorial ||= self * (self-1).factorial end end 0.instance_variable_set('@factorial',1) |
|
![]() |
| Outils de la discussion | |
|
|