Tuesday, January 09, 2007

Stringy Shortcuts [ String Methods ] - Ruby on Rails

Seven Satisfying Stringy Shortcuts

1: at (String)

>> "Finally, something useful!".at(6)
=> "y"

2: from and to (String)

>> "Chris the Person".from(6)
=> "the Person"
>> "Chris the Person".to(4)
=> "Chris"

3: first and last (String)

>> "Christmas Time".first
=> "C"
>> "Christmas Time".first(5)
=> "Chris"
>> "Christmas Time".last
=> "e"
>> "Christmas Time".last(4)
=> "Time"

4: each_char (String)

>> "Snow".each_char { |i| print i.upcase }
SNOW

5: starts_with? and ends_with? (String)

>> "Peanut Butter".starts_with? 'Peanut'
=> true
>> "Peanut Butter".ends_with? 'Nutter'
=> false

6: to_time and to_date (String)

>> "1985-03-13".to_time
=> Wed Mar 13 00:00:00 UTC 1985
>> "1985-03-13".to_date
=> #

7: transformations! (String)

Use these Methods

pluralize, singularize, camelize, titleize, underscore, dasherize, demodulize, tableize, classify, humanize, foreign_key, and constantize

>> "reindeer".pluralize
=> "reindeers"
>> "elves".singularize
=> "elf"
>> "christmas_carol".camelize
=> "ChristmasCarol"
>> "christmas_carol".camelize(:lower)
=> "christmasCarol"
>> "holiday_cheer".titleize
=> "Holiday Cheer"
>> "AdventCalendar-2006".underscore
=> "advent_calendar_2006"
>> "santa_Claus".dasherize
=> "santa-Claus"
>> "Holiday::December::Christmas".demodulize
=> "Christmas"
>> "SnowStorm".tableize
=> "snow_storms"
>> "snow_storms".classify
=> "SnowStorm"
>> "present_id".humanize
=> "Present"
>> "Present".foreign_key
=> "present_id"
>> "Cheer".constantize
NameError: uninitialized constant Cheer
>> "Christmas".constantize
=> Christmas

0 comments: