String class Documentation
Ruby has many classes.
Now we are going to see about String class.
String contains these methods in default.
%
*
+
<
<<
<=
<=>
==
===
=~
>
>=
[]
[]=
__id__
__send__
all?
any?
between?
capitalize
capitalize!
casecmp
center
chomp
chomp!
chop
chop!
class
clone
collect
concat
count
crypt
delete
delete!
detect
display
downcase
downcase!
dump
dup
each
each_byte
each_line
each_with_index
empty?
entries
eql?
equal?
extend
find
find_all
freeze
frozen?
gem
grep
gsub
gsub!
hash
hex
id
include?
index
inject
insert
inspect
instance_eval
instance_of?
instance_variable_defined?
instance_variable_get
instance_variable_set
instance_variables
intern
is_a?
is_binary_data?
is_complex_yaml?
kind_of?
length
ljust
lstrip
lstrip!
map
match
max
member?
method
methods
min
next
next!
nil?
object_id
oct
partition
private_methods
protected_methods
public_methods
reject
replace
require
require_gem
respond_to?
reverse
reverse!
rindex
rjust
rstrip
rstrip!
scan
select
send
singleton_methods
size
slice
slice!
sort
sort_by
split
squeeze
squeeze!
strip
strip!
sub
sub!
succ
succ!
sum
swapcase
swapcase!
taguri
taguri=
taint
tainted?
to_a
to_f
to_i
to_s
to_str
to_sym
to_yaml
to_yaml_properties
to_yaml_style
tr
tr!
tr_s
tr_s!
type
unpack
untaint
upcase
upcase!
upto
zip
RDoc Documentation:
This page provides Documentation for these methods But it will take some time.
So this article contains all the methods with the examples in one page.
Method | Example | Description |
---|---|---|
% | “%05d” % 123 #=> “00123”
“%-5s: %08x” % [ “ID”, self.id ] |
Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array containing the values to be substituted. See Kernel::sprintf for details of the format string. |
* | puts “jazzez”*2 => ‘jazzezjazzez’ | Copy—Returns a new String containing integer copies of the receiver. |
+ | puts “Welcome “+”jazzez” => ‘Welcome jazzez’ | Concatenation—Returns a new String containing other_str concatenated to str. |
< | puts “jazzez” < “hello” =>false puts “jazzez” < “ruby” => true |
Compares two objects based on the receiver‘s <=> method, returning true if it returns -1. |
<< | a = “hello ” a << “world” #=> “hello world” a.concat(33) #=> “hello world!” |
Append—Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation. |
<= | puts “jazzez” <= “hello” =>false puts “jazzez” <= “ruby” => true |
Compares two objects based on the receiver‘s <=> method, returning true if it returns -1 or 0. |
<=> | “abcdef” <=> “abcde” #=> 1 “abcdef” <=> “abcdef” #=> 0 “abcdef” <=> “abcdefg” #=> -1 “abcdef” <=> “ABCDEF” #=> 1 |
Comparison—Returns -1 if other_str is less than, 0 if other_str is equal to, and +1 if other_str is greater than str. If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one. If the variable $= is false, the comparison is based on comparing the binary values of each character in the string. In older versions of Ruby, setting $= allowed case-insensitive comparisons; this is now deprecated in favor of using String#casecmp. <=> is the basis for the methods <, <=, >, >=, and between?, included from module Comparable. The method String#== does not use Comparable#==. |
== | puts “jazzez”==”jazzez” => true puts “jazzez”==”welcome” =>false |
Equality—If obj is not a String, returns false. Otherwise, returns true if str <=> obj returns zero. |
=== | puts “jazzez”===”jazzez” => true puts “jazzez”===”welcome” =>false |
Case Equality—For class Object, effectively the same as calling #==, but typically overridden by descendents to provide meaningful semantics in case statements. |
=~ | “cat o’ 9 tails” =~ /\d/ #=> 7 “cat o’ 9 tails” =~ 9 #=> false |
Match—If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns false. |
> | puts “jazzez” >”hello” => true puts “jazzez” > “ruby” => false |
Compares two objects based on the receiver‘s <=> method, returning true if it returns 1. |
>= | puts “jazzez” >=”hello” => true puts “jazzez” >= “ruby” => false |
Compares two objects based on the receiver‘s <=> method, returning true if it returns 0 or 1. |
[] | a = “hello there” a[1] #=> 101 a[1,3] #=> “ell” a[1..3] #=> “ell” a[-3,2] #=> “er” a[-4..-2] #=> “her” a[12..-1] #=> nil a[-2..-4] #=> “” a[/[aeiou](.)\1/] #=> “ell” a[/[aeiou](.)\1/, 0] #=> “ell” a[/[aeiou](.)\1/, 1] #=> “l” a[/[aeiou](.)\1/, 2] #=> nil a[“lo”] #=> “lo” a[“bye”] #=> nil |
Element Reference—If passed a single Fixnum, returns the code of the character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end. |
__id__ | Document-method: object_id Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id. |
|
__send__ | class Klass def hello(*args) “Hello ” + args.join(‘ ‘) end end k = Klass.new k.send :hello, “gentle”, “readers” #=> “Hello gentle readers” |
Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj. |
all? | puts “jazzes”.all? => true | |
any? | puts “jazzez”.any? => true puts “”.any? => false |
|
between? | 3.between?(1, 5) #=> true 6.between?(1, 5) #=> false ‘cat’.between?(‘ant’, ‘dog’) #=> true ‘gnu’.between?(‘ant’, ‘dog’) #=> false |
Returns false if obj <=> min is less than zero or if anObject <=> max is greater than zero, true otherwise. |
capitalize | “hello”.capitalize #=> “Hello” “HELLO”.capitalize #=> “Hello” “123ABC”.capitalize #=> “123abc” |
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase. |
capitalize! | a = “hello” a.capitalize! #=> “Hello” a #=> “Hello” a.capitalize! #=> nil |
Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made. |
casecmp | “abcdef”.casecmp(“abcde”) #=> 1 “aBcDeF”.casecmp(“abcdef”) #=> 0 “abcdef”.casecmp(“abcdefg”) #=> -1 “abcdef”.casecmp(“ABCDEF”) #=> 0 |
Case-insensitive version of String#<=>. |
center | “hello”.center(4) #=> “hello” “hello”.center(20) #=> ” hello ” “hello”.center(20, ‘123’) #=> “1231231hello12312312” |
If integer is greater than the length of str, returns a new String of length integer with str centered and padded with padstr; otherwise, returns str. |
chomp | “hello”.chomp #=> “hello” “hello\n”.chomp #=> “hello” “hello\r\n”.chomp #=> “hello” “hello\n\r”.chomp #=> “hello\n” “hello\r”.chomp #=> “hello” “hello \n there”.chomp #=> “hello \n there” “hello”.chomp(“llo”) #=> “he” |
Returns a new String with the given record separator removed from the end of str (if present). If $/ has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is it will remove \n, \r, and \r\n). |
chomp! | Modifies str in place as described for String#chomp, returning str, or nil if no modifications were made. | |
chop | “string\r\n”.chop #=> “string” “string\n\r”.chop #=> “string\n” “string\n”.chop #=> “string” “string”.chop #=> “strin” “x”.chop.chop #=> “” |
Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn‘t end in a record separator. |
chop! | Processes str as for String#chop, returning str, or nil if str is the empty string. See also String#chomp!. | |
class | 1.class #=> Fixnum “jazzez”.class #=> String self.class #=> Object |
Returns the class of obj, now preferred over Object#type, as an object‘s type in Ruby is only loosely tied to that object‘s class. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby. |
clone | class Klass attr_accessor :str end s1 = Klass.new #=> # s1.str = “Hello” #=> “Hello” s2 = s1.clone #=> # s2.str[1,4] = “i” #=> “i” s1.inspect #=> “#” s2.inspect #=> “#” This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class. |
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup. |
collect | puts “jazzez”.collect => [“jazzez”] | |
concat | puts “jazzez”.concat(“123”) => “jazzez123” | |
count | a = “hello world” a.count “lo” #=> 5 a.count “lo”, “o” #=> 2 a.count “hello”, “^l” #=> 4 a.count “ej-m” #=> 4 |
Each other_str parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any other_str that starts with a caret (^) is negated. The sequence c1—c2 means all characters between c1 and c2. |
crypt | Applies a one-way cryptographic hash to str by invoking the standard library function crypt. The argument is the salt string, which should be two characters long, each character drawn from [a-zA-Z0-9./]. | |
delete | “hello”.delete “l”,”lo” #=> “heo” “hello”.delete “lo” #=> “he” “hello”.delete “aeiou”, “^e” #=> “hell” “hello”.delete “ej-m” #=> “ho” |
Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count. |
delete! | Performs a delete operation in place, returning str, or nil if str was not modified. | |
display | def display(port=$>) port.write self end For example: 1.display “cat”.display [ 4, 5, 6 ].display puts produces: 1cat456 |
Prints obj on the given port (default $>). Equivalent to: |
downcase | “hEllO”.downcase #=> “hello” | Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. The operation is locale insensitive—only characters “A’’ to “Z’’ are affected. |
downcase! | Downcases the contents of str, returning nil if no changes were made. | |
dump | Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped. | |
dup | Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance. This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class. |
|
each | print “Example one\n” “hello\nworld”.each {|s| p s} print “Example two\n” “hello\nworld”.each(‘l’) {|s| p s} print “Example three\n” “hello\n\n\nworld”.each(”) {|s| p s} produces: Example one “hello\n” “world” Example two “hel” “l” “o\nworl” “d” Example three “hello\n\n\n” “world” |
Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split on \n characters, except that multiple successive newlines are appended together. |
each_byte | “hello”.each_byte {|c| print c, ‘ ‘ } produces: 104 101 108 108 111 |
Passes each byte in str to the given block. |
each_line | puts “ravi \n raja \n”.each_line {puts “hi” } # => hi hi |
|
each_with_index | puts “ravi \n raja \n”.each_with_index {puts “hi” } # => hi hi |
|
empty? | “hello”.empty? #=> false “”.empty? #=> true |
Returns true if str has a length of zero. |
entries | puts “ravi \n raje \n jazzez \n raveendran”.entries
# => [“ravi \n”, ” raje \n”, ” jazzez \n”, ” raveendran”] |
|
eql? | 1 == 1.0 #=> true 1.eql? 1.0 #=> false |
Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so: |
equal? | Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so: |
|
extend | module Mod def hello “Hello from Mod.\n” end end class Klass k = Klass.new |
Adds to obj the instance methods from each module given as a parameter. |
freeze | a = [ “a”, “b”, “c” ] a.freeze a << “z” produces: prog.rb:3:in `<<‘: can’t modify frozen array (TypeError) from prog.rb:3 |
Prevents further modifications to obj. A TypeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?. |
frozen? | a = [ “a”, “b”, “c” ] a.freeze #=> [“a”, “b”, “c”] a.frozen? #=> true |
Returns the freeze status of obj. |
gsub | “hello”.gsub(/[aeiou]/, ‘*’) #=> “h*ll*” “hello”.gsub(/([aeiou])/, ‘<\1>’) #=> “hll” “hello”.gsub(/./) {|s| s[0].to_s + ‘ ‘} #=> “104 101 108 108 111 “ |
The result inherits any tainting in the original string or any supplied replacement string. |
gsub! | Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. | |
hash | Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used. | |
hex | “0x0a”.hex #=> 10 “-1234”.hex #=> -4660 “0”.hex #=> 0 “wombat”.hex #=> 0 |
Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error. |
id | Soon-to-be deprecated version of Object#object_id. | |
include? | “hello”.include? “lo” #=> true “hello”.include? “ol” #=> false “hello”.include? ?h #=> true |
Returns true if str contains the given string or character. |
index | “hello”.index(‘e’) #=> 1 “hello”.index(‘lo’) #=> 3 “hello”.index(‘a’) #=> nil “hello”.index(101) #=> 1 “hello”.index(/[aeiou]/, -3) #=> 4 |
Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search. |
inject | puts “jazzez”.inject => “jazzez” | |
insert | “abcd”.insert(0, ‘X’) #=> “Xabcd” “abcd”.insert(3, ‘X’) #=> “abcXd” “abcd”.insert(4, ‘X’) #=> “abcdX” “abcd”.insert(-3, ‘X’) #=> “abXcd” “abcd”.insert(-1, ‘X’) #=> “abcdX” |
Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is insert aString so that it starts at the given index. |
inspect | str = “hello” str[3] = 8 str.inspect #=> “hel10o” “ravi \n raje \n jazzez \n raveendran”.inspect |
Returns a printable version of str, with special characters escaped. |
instance_eval | class Klass def initialize @secret = 99 end end k = Klass.new k.instance_eval { @secret } #=> 99 |
Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj‘s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors. |
instance_of? | Returns true if obj is an instance of the given class. See also Object#kind_of?. | |
instance_variable_defined? | class Fred def initialize(p1, p2) @a, @b = p1, p2 end end fred = Fred.new(‘cat’, 99) fred.instance_variable_defined?(:@a) #=> true fred.instance_variable_defined?(“@b”) #=> true fred.instance_variable_defined?(“@c”) #=> false |
Returns true if the given instance variable is defined in obj. |
instance_variable_get | class Fred def initialize(p1, p2) @a, @b = p1, p2 end end fred = Fred.new(‘cat’, 99) fred.instance_variable_get(:@a) #=> “cat” fred.instance_variable_get(“@b”) #=> 99 |
Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name. |
instance_variable_set | class Fred def initialize(p1, p2) @a, @b = p1, p2 end end fred = Fred.new(‘cat’, 99) fred.instance_variable_set(:@a, ‘dog’) #=> “dog” fred.instance_variable_set(:@c, ‘cat’) #=> “cat” fred.inspect #=> “#” |
Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class‘s author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call. |
instance_variables | class Fred attr_accessor :a1 def initialize @iv = 3 end end Fred.new.instance_variables #=> [“@iv”] |
Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable. |
intern | “Koala”.intern #=> :Koala | Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name. |
is_a? | module M; end class A include M end class B < A; end class C < B; end b = B.new b.instance_of? A #=> false b.instance_of? B #=> true b.instance_of? C #=> false b.instance_of? M #=> false b.kind_of? A #=> true b.kind_of? B #=> true b.kind_of? C #=> false b.kind_of? M #=> true |
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj. |
is_binary_data? | puts “jazzez”.is_binary_data? => false | |
length | puts “raveendran”.length => 10 | Returns the length of str. |
ljust | “hello”.ljust(4) #=> “hello” “hello”.ljust(20) #=> “hello ” “hello”.ljust(20, ‘1234’) #=> “hello123412341234123” |
If integer is greater than the length of str, returns a new String of length integer with str left justified and padded with padstr; otherwise, returns str. |
lstrip | ” hello “.lstrip #=> “hello ” “hello”.lstrip #=> “hello” |
Returns a copy of str with leading whitespace removed. See also String#rstrip and String#strip. |
lstrip! | ” hello “.lstrip #=> “hello ” “hello”.lstrip! #=> nil |
Removes leading whitespace from str, returning nil if no change was made. See also String#rstrip! and String#strip!. |
map | It gives array format and then useful o continue further. | |
match | ‘hello’.match(‘(.)\1’) #=> # ‘hello’.match(‘(.)\1’)[0] #=> “ll” ‘hello’.match(/(.)\1/)[0] #=> “ll” ‘hello’.match(‘xx’) #=> nil |
Converts pattern to a Regexp (if it isn‘t already one), then invokes its match method on str. |
member? | puts “jazzez”.member?(“jazz”) => false puts “jazzez”.member?(“jazzez”) => true |
|
method | class Demo def initialize(n) @iv = n end def hello() “Hello, @iv = #{@iv}” end end k = Demo.new(99) l = Demo.new(‘Fred’) |
Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj‘s object instance, so instance variables and the value of self remain available. |
methods | class Klass def kMethod() end end k = Klass.new k.methods[0..9] #=> [“kMethod”, “freeze”, “nil?”, “is_a?”, “class”, “instance_variable_set”, “methods”, “extend”, “__send__”, “instance_eval”] k.methods.length #=> 42 |
Returns a list of the names of methods publicly accessible in obj. This will include all the methods accessible in obj‘s ancestors. |
next | puts “a”.next =>” b” puts “z”.next => “aa” puts “#”.next => “$” puts “1”.next => “2” puts “9”.next => “10” |
|
next! | Same as next but it gives the changed format of output | |
nil? | nil.nil? => true .nil? => false Only the object nil responds true to nil?. |
call_seq: |
object_id | Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id. | |
oct | “123”.oct #=> 83 “-377”.oct #=> -255 “bad”.oct #=> 0 “0377bad”.oct #=> 255 |
Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. Returns 0 if the conversion fails. |
partition | a=”jazzez” puts a.partition{} => [[],[“jazzez”]] puts a.partition{1} => [[“jazzez”],[]] |
|
private_methods | Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed. | |
protected_methods | Returns the list of protected methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed. | |
public_methods | Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed. | |
reject | Returns an array element | |
replace | s = “hello” #=> “hello” s.replace “world” #=> “world” |
Replaces the contents and taintedness of str with the corresponding values in other_str. |
respond_to? | Returns true> if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true. | |
reverse | “stressed”.reverse #=> “desserts” | Returns a new string with the characters from str in reverse order. |
reverse! | Reverses str in place. | |
rindex | “hello”.rindex(‘e’) #=> 1 “hello”.rindex(‘l’) #=> 3 “hello”.rindex(‘a’) #=> nil “hello”.rindex(101) #=> 1 “hello”.rindex(/[aeiou]/, -2) #=> 1 |
Returns the index of the last occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to end the search—characters beyond this point will not be considered. |
rjust | “hello”.rjust(4) #=> “hello” “hello”.rjust(20) #=> ” hello” “hello”.rjust(20, ‘1234’) #=> “123412341234123hello” |
If integer is greater than the length of str, returns a new String of length integer with str right justified and padded with padstr; otherwise, returns str. |
rstrip | ” hello “.rstrip #=> ” hello” “hello”.rstrip #=> “hello” |
Returns a copy of str with trailing whitespace removed. See also String#lstrip and String#strip. |
rstrip! | ” hello “.rstrip #=> ” hello” “hello”.rstrip! #=> nil |
Removes trailing whitespace from str, returning nil if no change was made. See also String#lstrip! and String#strip!. |
scan | a = “cruel world” a.scan(/\w+/) #=> [“cruel”, “world”] a.scan(/…/) #=> [“cru”, “el “, “wor”] a.scan(/(…)/) #=> [[“cru”], [“el “], [“wor”]] a.scan(/(..)(..)/) #=> [[“cr”, “ue”], [“l “, “wo”]] And the block form: a.scan(/\w+/) {|w| print “<<#{w}>> ” } print “\n” a.scan(/(.)(.)/) {|x,y| print y, x } print “\n” produces: <> <> rceu lowlr |
Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group. |
send | class Klass def hello(*args) “Hello ” + args.join(‘ ‘) end end k = Klass.new k.send :hello, “gentle”, “readers” #=> “Hello gentle readers” |
Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj. |
singleton_methods | module Chatty def Chatty.singleton_method_added(id) puts “Adding #{id.id2name}” end def self.one() end def two() end def Chatty.three() end end produces: Adding singleton_method_added Adding one Adding three |
Invoked as a callback whenever a singleton method is added to the receiver. |
size | puts “jazzez”.size => 6 | |
slice | puts “jazzez”.slice(“z”) => “z” puts “jazzez”.slice(“y”) => nil |
|
slice! | puts “jazzez”.slice!(“z”) => “z” puts “jazzez”.slice!(“y”) => nil |
|
split | ” now’s the time”.split #=> [“now’s”, “the”, “time”] ” now’s the time”.split(‘ ‘) #=> [“now’s”, “the”, “time”] ” now’s the time”.split(/ /) #=> [“”, “now’s”, “”, “the”, “time”] “1, 2.34,56, 7”.split(%r{,\s*}) #=> [“1”, “2.34”, “56”, “7”] “hello”.split(//) #=> [“h”, “e”, “l”, “l”, “o”] “hello”.split(//, 3) #=> [“h”, “e”, “llo”] “hi mom”.split(%r{\s*}) #=> [“h”, “i”, “m”, “o”, “m”] “mellow yellow”.split(“ello”) #=> [“m”, “w y”, “w”] |
Divides str into substrings based on a delimiter, returning an array of these substrings. If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored. If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ’ were specified. If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed. |
squeeze | “yellow moon”.squeeze #=> “yelow mon” ” now is the”.squeeze(” “) #=> ” now is the” “putters shoot balls”.squeeze(“m-z”) #=> “puters shot balls” |
Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character. |
squeeze! | Squeezes str in place, returning either str, or nil if no changes were made. | |
strip | ” hello “.strip #=> “hello” “\tgoodbye\r\n”.strip #=> “goodbye” |
Returns a copy of str with leading and trailing whitespace removed. |
strip! | Removes leading and trailing whitespace from str. Returns nil if str was not altered. | |
sub | “hello”.sub(/[aeiou]/, ‘*’) #=> “h*llo” “hello”.sub(/([aeiou])/, ‘<\1>’) #=> “hllo” “hello”.sub(/./) {|s| s[0].to_s + ‘ ‘ } #=> “104 ello” |
Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is /\d/ will match a digit, but ’\d‘ will match a backslash followed by a ‘d’). If the method call specifies replacement, special variables such as $& will not be useful, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, etc., may be used. In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $’ will be set appropriately. The value returned by the block will be substituted for the match on each call. The result inherits any tainting in the original string or any supplied replacement string. |
sub! | Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed. | |
succ | “abcd”.succ #=> “abce” “THX1138”.succ #=> “THX1139” “<>”.succ #=> “<>” “1999zzz”.succ #=> “2000aaa” “ZZZ9999”.succ #=> “AAAA0000” “***”.succ #=> “**+” |
Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set‘s collating sequence. If the increment generates a “carry,’’ the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary. |
succ! | Equivalent to String#succ, but modifies the receiver in place. | |
sum | Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2n – 1. This is not a particularly good checksum. | |
swapcase | “Hello”.swapcase #=> “hELLO” “cYbEr_PuNk11”.swapcase #=> “CyBeR_pUnK11” |
Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. |
swapcase! | Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. | |
taint | Marks obj as tainted—if the $SAFE level is set appropriately, many method calls which might alter the running programs environment will refuse to accept tainted strings. | |
tainted? | Returns true if the object is tainted. | |
to_a | self.to_a #=> -:1: warning: default `to_a’ will be obsolete “hello”.to_a #=> [“hello”] Time.new.to_a #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, “CDT”] |
Returns an array representation of obj. For objects of class Object and others that don‘t explicitly override the method, the return value is an array containing self. However, this latter behavior will soon be obsolete. |
to_f | “123.45e1”.to_f #=> 1234.5 “45.67 degrees”.to_f #=> 45.67 “thx1138”.to_f #=> 0.0 |
Returns the result of interpreting leading characters in str as a floating point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. This method never raises an exception. |
to_i | “12345”.to_i #=> 12345 “99 red balloons”.to_i #=> 99 “0a”.to_i #=> 0 “0a”.to_i(16) #=> 10 “hello”.to_i #=> 0 “1100101”.to_i(2) #=> 101 “1100101”.to_i(8) #=> 294977 “1100101”.to_i(10) #=> 1100101 “1100101”.to_i(16) #=> 17826049 |
Returns the result of interpreting leading characters in str as an integer base base (2, 8, 10, or 16). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception. |
to_s | Returns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns “main.’‘ | |
to_str | Returns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns “main.’‘ | |
to_sym | “Koala”.intern #=> :Koala s = ‘cat’.to_sym #=> :cat s == :cat #=> true s = ‘@cat’.to_sym #=> :@cat s == :@cat #=> true This can also be used to create symbols that cannot be represented using the :xxx notation. ‘cat and dog’.to_sym #=> :”cat and dog” |
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name. |
tr | “hello”.tr(‘aeiou’, ‘*’) #=> “h*ll*” “hello”.tr(‘^aeiou’, ‘*’) #=> “*e**o” “hello”.tr(‘el’, ‘ip’) #=> “hippo” “hello”.tr(‘a-y’, ‘b-z’) #=> “ifmmp” |
Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character. Both strings may use the c1—c2 notation to denote ranges of characters, and from_str may start with a ^, which denotes all characters except those listed. |
tr! | Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. | |
tr_s | “hello”.tr_s(‘l’, ‘r’) #=> “hero” “hello”.tr_s(‘el’, ‘*’) #=> “h*o” “hello”.tr_s(‘el’, ‘hx’) #=> “hhxo” |
Processes a copy of str as described under String#tr, then removes duplicate characters in regions that were affected by the translation. |
tr_s! | Performs String#tr_s processing on str in place, returning str, or nil if no changes were made. | |
type | Deprecated synonym for Object#class. | |
unpack | “abc abc “.unpack(‘A6Z6’) #=> [“abc”, “abc “] “abc “.unpack(‘a3a3’) #=> [“abc”, ” 0000″] “abc abc “.unpack(‘Z*Z*’) #=> [“abc “, “abc “] “aa”.unpack(‘b8B8’) #=> [“10000110”, “01100001”] “aaa”.unpack(‘h2H2c’) #=> [“16”, “61”, 97] “\xfe\xff\xfe\xff”.unpack(‘sS’) #=> [-2, 65534] “now=20is”.unpack(‘M*’) #=> [“now is”] “whole”.unpack(‘xax2aX2aX1aX2a’) #=> [“h”, “e”, “l”, “l”, “o”] |
Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (“*’’) will use up all remaining elements. The directives sSiIlL may each be followed by an underscore (“_’’) to use the underlying platform‘s native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. See also Array#pack. |
untaint | Removes the taint from obj. | |
upcase | “hEllO”.upcase #=> “HELLO” | Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive—only characters “a’’ to “z’’ are affected. |
upcase! | Upcases the contents of str, returning nil if no changes were made. | |
upto | “a8”.upto(“b6”) {|s| print s, ‘ ‘ } for s in “a8”..”b6″ print s, ‘ ‘ end produces: a8 a9 b0 b1 b2 b3 b4 b5 b6 a8 a9 b0 b1 b2 b3 b4 b5 b6 |
Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block. The String#succ method is used to generate each value. |
cool 😉
super machi
So what is the point of just copying and pasting massive chunks of the ruby manual? Unless of course it’s just an aide memoir, but really it just looks like you think are Matz.
Hi Matt,
I agree your comment.I spent more time to get few String class method details from http://www.ruby-doc.org/core/ . Because all the method details were not available in single page. This article gives “All-in-one-page”. Thats all.
Thanks,
P.Raveendran