Ruby: String

intro

  • strings are a sequences of characters.
  • the name comes from the fact that the characters are strung together.

string format

  • single quoted ('string') : basic string, faster than double quoted.
  • double quoted ("string") : support interpolation and escape sequences.
  • back quoted (`string`): execute as command in bin/rails folder.
  • other.%q quoted (%q(foo bar): string without interpolation.
  • other.%Q quoted (%Q(foo #{bar})): string with interpolation.

fancy way

  • concate: 'foo' << 'bar'
  • multiply: 'foo' * 1000
  • 'aaa'.next #=> 'aab'
  • '111'.next #=> '112'

search methods

  • check whether a string contains any given character or substring.
  • e.g.: #include?, #start_with?. #end_with?, #index, etc...

case change methods

  • e.g.: #upcase, #downcase, #swapcase, #capitalize, etc...

split methods

  • split strings by particular characters.
  • e.g. combine #split and regex to operate.
  • like split strings on newlines, and parse date in csv.

concatenate methods

  • create new string by adding two string together.
  • efficiency: '<<' same as '#concat' better than '+'
  • << and #concat change the original string object.

replace substring

  • first search for substrings or use regex.
  • e.g.: #sub(a, b); #gsub(a, b); #gsub(/regex/, b);
  • regex are a concise and flex means for 'matching' strings.
  • if you want to implement a parser, #match might be a good friend :P

chop and chomp

  • todo

你可能感兴趣的:(Ruby: String)