symbol | what it does |
---|---|
+ | concatenate |
<< | append |
* | repetition |
[] | indexing |
<=> | comparison, returns -1 for less, 0 for equal, 1 for greater |
=> -1
>> “a” <=> “a”
=> 0
>> “b” <=> “a”
=> 1
Some more string methods, using examples:
=> “hello”
>> s.concat(” world”)
=> “hello world”
# .concat is same as +
=> “hello there world”
# inserts substring into part of the string
>> s.slice(0,5)
=> “hello”
# non-destructive slice, returns a substring
=> “hello there world”
>> s.slice!(5,6)
=> ” there”
>> s
=> “hello world”
Note that the destructive slice! method deletes a section of the string itself (the actual object). same as s[5,6]=””. However, it returns the deleted substring, while altering the original string. (Notice that slice! in this case returned ” there” and s was changed to “hello world”)
=> true
# same as ==
=> 11
In Ruby 1.8, counts the number of characters; in Ruby 1.9, counts the number of bytes.
=> 11
Size is same as length
=> 11
Length in bytes; Ruby 1.9 ONLY
=> false
>> “”.empty?
=> true
=> 6
>> s.index(‘nothere’)
=> nil
Returns the position of a substring or pattern match; can also be used with regular expressions. Returns nil if no match is found.
Also try:
>> true
=> s.end_with?(“world”)
>> true
>> true
# test for presence of the substring within the string