PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/ruby/string_examples.yml

https://github.com/felixgao/chitsheet
YAML | 72 lines | 43 code | 12 blank | 17 comment | 0 complexity | 4f44d0c0478d357fce22ebc2ae3b47e5 MD5 | raw file
  1. ---
  2. ruby_string_examples: |-
  3. # Use single quotes \' to create a literal string.
  4. # Inside a quoted string #{foobar}, \, ... is not interpreted.
  5. %q = single quoted
  6. # e.g.
  7. %q{ 'single quoted text' doesn't need to be escaped} => " 'single quoted text' doesn't need to be escaped"
  8. %Q = double quoted
  9. # e.g. %Q{ "doublee quoted text" doesn't need to be escaped}
  10. # Can replace curly braces with any other character, like a dot "."
  11. %q = single quoted
  12. # e.g.
  13. %q. 'single quoted text' doesn't need to be escaped. => " 'single quoted text' doesn't need to be escaped"
  14. # here document
  15. mystring = <<EOS
  16. this is a
  17. mulitword
  18. string
  19. EOS
  20. # Most operations don't change the orginal string.
  21. # Unless the bang \! is used or the method implies it, replace method.
  22. "a" + "b" => "ab"
  23. "a" << "b" => "ab"
  24. b = "some string"
  25. "a#{b}" => "asome string"
  26. "%d some text more text" % 33 => "33 some text more text"
  27. "%d some text more text" % [55] => "55 some text more text"
  28. "some int %d some float %f" % [55, 44.7] => "some int %d some float %f" % [55, 44.7]
  29. # Massaging strings
  30. # Default will create a new string. For in-place changes add bang ! to method name
  31. capitilize "tom".captilize => "Tom"
  32. upcase "tom".upcase => "TOM"
  33. downcase "TOM".downcase => "tom"
  34. swapcase "tom".swapcase = "TOM"
  35. strip " lose the outer spaces ".strip => "lose the outer spaces"
  36. rstrip " lose the right spaces ".rstrip => " lose the outer spaces"
  37. lstrip " lose the left spaces ".lstrip => "lose the outer spaces "
  38. chop "remove the last character".chop => "remove the last characte"
  39. chomp "remove trailing newline\n".chomp => "remove the the trailing newline"
  40. reverse " gnirts eht esrever".reverse => "reverse the string"
  41. # Getting character
  42. "foobar"[3] => 98 # ascii number for 'b'
  43. "foobar"[3].chr => "b"
  44. "foobar"[3,2] => "ba"
  45. "foobar"[-2].chr => "a"
  46. # Getting Substrings
  47. "This is a string"[5, 4] => "is a"
  48. "foo bar baz"[/foo (\w+) baz/, 1] => "bar"
  49. # Replacement
  50. foo = "bar"
  51. foo.replace "hush" => "hush"
  52. foo = "This is a string"
  53. foo[5, 4] => "is a"
  54. "Some string with whitespace\n and\t\tlines".gsub(/\s+/,'_') => "Some_string_with_whitespace_and_lines"
  55. # Equality
  56. "a" == "a" => true
  57. # they are not the place in memory. different obj ids
  58. "a".equal? "a" => false
  59. # Comparision
  60. <=> spaceship operator, return -1, 0, 1 for less than, equal to, greater than