Using self as the first argument in ruby instance methods -


this string#dasherize activesupport::inflector:

def dasherize(underscored_word)   underscored_word.tr('_', '-') end 

it replaces underscores in string dashes.

'puni_puni'.dasherize # => "puni-puni" 

the receiver used argument method.

activesupport::inflector.dasherize(puni_puni) # => "puni-puni" 

when try similar, doesn't work:

module newdash     def new_dasherize(underscored_word)         underscored_word.tr('_', '-')     end end  string.include newdash  t = "t_e_s_t" t.new_dasherize # => argumenterror: wrong number of arguments (0 1) t.new_dasherize(t) # => "t-e-s-t" 

how can replicate behavior, , technical term it?

you can in couple different ways. lclk mentioned 1 way, setting self default underscored_word in argument list. way referencing self directly

module newdash   def new_dasherize     self.tr('_', '-')   end end  string.include newdash 

after running that, can call new_dasherize directly on string itself

>> 'puni_puni'.new_dasherize => "puni-puni" 

you can achieve exact same thing, activesupport style, this

class string   def new_dasherize     self.tr('_', '-')   end end 

that's activesupport does, open string class (check out) , tack on methods. happen delegate implementation of dasherize method activesupport::inflections

if here, you'll see activesupport implements dasherize method.

the technical term "extending object", though i'm not positive on that.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -