Getting Started with Ruby: How to create and use string

Source: Internet
Author: User

This article focuses on the creation and use of strings in ruby, hoping to help friends who are learning ruby (http://www.maiziedu.com/course/ruby-px/) strings.
String creation: A string is also an object. Like other general objects, it can be created using the new method.
eg:
str = String.new
str << 72 << 101 << 108 << 108 << 111
p str # => "Hello"
String literals: write the string you want to create in a pair (") or (')
eg:
"Hello"
"Chinese"
‘Single quoted’
‘Contains line breaks’
Escape characters: Strings enclosed in double quotes can also use escape characters. Escape characters are represented by a backslash "\" followed by a specific token.
eg: "\ n" "\ 0"
Expansion of formulas: Formulas can be expanded in double-quoted string literals, but not in single-quoted strings. The so-called formula expansion means that the part enclosed in # {...} in the string will be interpreted as a Ruby formula, and its value will be displayed in the string.
eg:
a = 2
"The value of a is # {a}"
"The 5th power of a is # {a ** 5}"
Backquoted strings: If a string is quoted with a backquote (`), it becomes a special string literal. The content in backticks will be executed as a shell command, and the output of the command will be converted into a string.
eg:
p `date`
p `pwd`
Percent sign notation: The backslash is not used to escape the quote characters in the percent sign notation, so the use of escape characters is reduced when representing strings containing many quotes.
eg:
% q [string containing "# =>"
% Q [a string with ‘] # =>’
Regular expressions: Regular expressions are mini-programming languages that perform certain pattern matching on strings. When you find or replace a part of a string that has a specific pattern, you can easily express the pattern.
Regular expression literals: Regular expression (Regexp) objects are created from regular expression literals. Regular expression literals are expressions enclosed in slashes like / Regexp /. In addition to using slashes, you can also use percent sign notation, like% r! Regexp !. And the escape character formula expansion in regular expression literals can also be used. parameter! Indicates that the regular expression is not case sensitive.
Manipulating strings:
eg:
story = << EOS
Solomon Grundy,
Born on Monday,
Christened on Tuseday,
Married on Wednesday,
Took ill on Thursday,
Worse on Friday,
Died on Saturday,
Buried on Sunday,
This is the end
Of Solomon Grundy.
EOS
#Operate characters based on position
p story [0], story [1], story [2] # => "S", "o", "l"
p story [187] # => nil
#Negative position
p story [-1], story [-2], story [-3], story [-4] # => "\ n", ".", "y", "d"
p story [8, 6] # => "Grundy" operates with position and length
p story [8 ... 14] # => "Grundy" Operate with ranges
p story ["Monday"] # => "Monday" operates with substrings
p story [/ \ w + sday /] # => "Wednesday" operate with regular expressions
Update: String objects are mutable in Ruby, so the contents of strings are also mutable.
eg:
story ["Solomon Grundy"] = "Hippopotamus"
print story
# => Hippopotamus
#Born on Monday,
#Christened on Tuseday,
#Married on Wednesday,
#Took ill on Thursday,
#Worse on Friday,
#Died on Saturday,
#Buried on Sunday,
#This is the end
#Of Solomon Grundy.
String operations:
eg1: connect
"str" + "ing" # => "string"
str = "str"; str << "ing"
p str # => "string" destructive join operator <<
eg2: Duplicate
"Look!" * 3 # => "Look! Look! Look!"
eg3: Split: split a string into multiple strings, you can use the split method, and substitute regular expressions in its parameters.
"a, bb, ccc, dddd" .split (/, /) # => ["a", "bb", "ccc", "dddd"]
"string" .split (//) # => ["s", "t", "r", "i", "n", "g"]
eg4: other
"string" .reverse # => "gnirts" How to reverse a string
"\ n \ rstring" .strip # => "string" method to remove whitespace at the beginning and end of a string
"string". length # => 6 calculate string length
eg5: Iteration: a method to perform repeated operations on a string
"str". each_byte do | byte |
      p byte # => 115, 116, 114
end
story. each_line do | line |
     print line
end
"String". Each_char do | char |
       p char # => "S", "t", "r", "i", "n", "g"
end
eg6: Format
printf ("% 04d", 3) # => "0003" 4 digits, filled with 0 in front
printf ("% 08.4f", Math :: PI * 10) # => "031.4159"
printf ("hex =% X, oct =% o", 10,10) # => "hex = A, oct = 12"
String #% has the same functionality and is more concise to use.
p "% 04d"% 3
p "% 08.4f"% (Math :: PI * 10)
p "hex =% X, oct =% o"% [10, 10]
eg7: Encoding
"Hello". Encoding # => <Encoding: UTF-8>
Encoding. Name_list #List the encodings available now
Encoding. Find ("CP1258") #Get Encoding encoding object
eg8: Magic Comment
#-*-coding: utf-8-*-or # vim: fileencoding = UTF-8
With such a comment, Ruby treats the source code as UTF-8. Add such a comment to the beginning of the source code when using it.
eg8: encoding change: use String # encode method to change the encoding of the string
#-*-coding: utf-8-*-
utf = "China"
p utf. encoding # => # <Encoding: UTF-8>
sjis = utf. encode ("Shift_JIS")
p sjis. encoding # => # <Encoding: Shift_JIS>
Comparison of strings: Strings are equal only if the byte tables are the same and the encoding is the same.



Ruby entry knowledge: the creation and use of string in detail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.