Wednesday, 28 May 2008

Ruby String Functions


  • “i got what i want”.count “i” #=> 2
  • “i got what i want”.delete “i” #=> ” got what want”
  • “hello”.gsub(/[aeiou]/, ‘*’) #=> “h*ll*”
  • “hello”.sub(/[aeiou]/, ‘*’) #=> “h*llo”
  • “hello”.tr(‘aeiou’, ‘*’) #=> “h*ll*”
  • “hello”.index(‘e’) #=> 1
  • “hello”.rindex(‘l’) #=> 3(last occurrence)
  • “abcd”.insert(3, ‘X’) #=> “abcXd”
  • ‘cat’.to_sym #=> :cat
  • “hello”.ljust(20) #=> “hello “
  • “hello”.ljust(20, ’1234′) #=> “hello123412341234123″
  • “hello”.rjust(20, ’1234′) #=> “123412341234123hello”
  • ” hello “.rstrip #=> ” hello”
  • ” hello “.lstrip #=> “hello “
  • ” hello “.strip #=> “hello”
  • a = “cruel world”
  • a.scan(/\w+/) #=> ["cruel", "world"]
  • a.scan(/…/) #=> ["cru", "el ", "wor"]
  • a.scan(/(…)/) #=> [["cru"], ["el "], ["wor"]]
  • a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]]
  • “1,2,,3,4,,”.split(‘,’) #=> ["1", "2", "", "3", "4"]
  • “putters shoot balls”.squeeze(“m-z”) #=> “puters shot balls”
  • “Finally, something useful!”.at(6) #=> “y”
  • “Chris the Person”.from(6) #=> “the Person”
  • “Chris the Person”.to(4) #=> “Chris”
  • “Christmas Time”.first #=> “C”
  • “Christmas Time”.first(5) #=> “Chris”
  • “Christmas Time”.last #=> “e”
  • “Christmas Time”.last(4) #=> “Time”
  • “Snow”.each_char { |i| print i.upcase } #=>SNOW
  • “Peanut Butter”.starts_with? ‘Peanut’ #=> true
  • “Peanut Butter”.ends_with? ‘Nutter’ #=> false
  • “1985-03-13″.to_time #=> Wed Mar 13 00:00:00 UTC 1985
  • “1985-03-13″.to_date #=> #
  • “stressed”.reverse #=> “desserts”
  • “Hello”.swapcase #=> “hELLO”
  • “hEllO”.upcase #=> “HELLO”
  • “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