Categories
Programming

Ruby Strings

symbol what it does
+ concatenate
<< append
* repetition
[] indexing
<=> comparison, returns -1 for less, 0 for equal, 1 for greater
>> “a” <=> “b”
=> -1
>> “a” <=> “a”
=> 0
>> “b” <=> “a”
=> 1

Some more string methods, using examples:

>> s = “hello”
=> “hello”

>> s.concat(” world”)
=> “hello world”
# .concat is same as +

>> s.insert(5, ” there”)
=> “hello there world”
# inserts substring into part of the string

>> s.slice(0,5)
=> “hello”
# non-destructive slice, returns a substring

>> s = “hello there world”
=> “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”)

>> s.eql?(“hello world”)
=> true
# same as ==
>> s.length
=> 11

In Ruby 1.8, counts the number of characters; in Ruby 1.9, counts the number of bytes.

>> s.size
=> 11

Size is same as length

>> s.bytesize
=> 11

Length in bytes; Ruby 1.9 ONLY

>> s.empty?
=> false
>> “”.empty?
=> true
>> s.index(‘w’)
=> 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:

=> s.start_with?(“hell”)
>> true
=> s.end_with?(“world”)
>> true
=> s.include?(“ll”)
>> true

# test for presence of the substring within the string

Leave a Reply

OR LOG IN WITH




Your email address will not be published. Required fields are marked *