Ruby strings, symbols, numbers, dates

Source: Internet
Author: User
Tags arithmetic chop crypt flush hash numeric ord time and date


String



The two classes, String and Symbol, provide the ability to represent text and work with text. The two classes are very different.



String representation



A string is generally wrapped in a set of quotation marks:



"That's a string."
Single quotes are OK:



' I'm also a string '
Double quotes are used when using character interpolation:



Puts "two plus two equals #{2 + 2}"
Puts ' two plus two equals #{2 + 2} '
The contents of the output are:



Two plus two equals 4.
Two plus two equals #{2 + 2}
The difference between a single citation and a double lead in escape:


The

puts backslashes (\) have to is escaped in double quotes.
puts ' can just type \ Once in a single quoted string. '
puts "But whichever type of quotation mark use ..."
puts "... you have to escape its quotation symbol, such as \"."
puts ' that applies to \ ' in single-quoted strings too. '
puts ' backslash-n just looks like \ n between single quotes. '
puts "But it means newline\nin a double-quoted string."
puts ' Same with \ T, which comes out as \ t with single quotes ... '
puts ... but inserts a tab character:\tinside do Uble quotes. "
puts "You can escape the backslash to get \\n and \\t with double quotes." The
output is:



Backslashes (\) have to is escaped in double quotes.
can just type \ Once in a single quoted string.
But whichever type of quotation mark use ...
Have to escape its quotation symbol, such as ".
That's applies to ' in single-quoted strings too.
Backslash-n just looks like \ n between single quotes.
But It means newline
In a double-quoted string.
Same with \ t, which comes out as \ t with single quotes ...
... but inserts a tab character:inside double quotes.
You can escape the backslash. \ t with double quotes.
6:59 * *



7:24 * *



Other Referral mechanisms



There is also a reference mechanism,%char{text}, the following%q generates a single quote character:



Puts%q{you Needn ' t escape apostrophes when using%q.}
Because the string above is not marked with single quotes, the apostrophe in the string does not have to escape.



Double quotes can also be used with%q,%{}. The separator can also be very casual:



%q-a string-
%q/another string/
%[yet another string]
Here document



Here-doc, can be multiple lines of string:



>> Text = <<eom
This is the ' a ' of text.
This is the second line.
Now we ' re done.
EOM
=> ' This is the ' the ' 's ' Text.\nthis is the second line.\nnow we ' re done.\n '
<<eom start, to the end of EOM, EOM is a separator, it can be any string, EOM is the convention, meaning the word "." To align Left, you do not want to align left to add a-:



>> Text = <<-eom
The EOM doesn ' t have to be flush left!
EOM
=> "The EOM doesn ' t have to be flush left!\n"
The default Here-docs, like a double quote string, explains the character interpolation within it, as well as some escape characters, such as \ n or \ t. If you need to make here-doc like a single quote string, you can do this:



>> text = <<-' EOM '
single-quoted!
Note the literal \ n.
and the literal #{2+2}.
EOM
=> "Single-quoted!\nnote the literal \\n.\nAnd the literal \#{2+2}.\n"
>> puts text
single-quoted!
Note the literal \ n.
and the literal #{2+2}.
=> Nil
Try this again:



>> A = <<eom.to_i * 10
5
EOM
=> 50
Try this again:



>> array = [1,2,3,<<eom,4]
This is the Here-doc.
It becomes array[3]
EOM
=> [1, 2, 3, "This is the here-doc.\nit becomes array[3]\n", 4]
As a method parameter:



Do_something_with_args (A, B, <<eom)
Http://some_very_long_url_or_other_text_best_put_on_its_own_line
EOM
String handling



Get and set substring



The [] operator can get a character from a position in a string. An index number is provided, the index number is zero-based, and the index of negative numbers refers to the last forward number from the string.



Try this:



>> string = ' Ruby is a cool language. '
=> "Ruby is a cool language."
>> String[5]
=> "I"
>> string[-12]
=> "O"
Intercept a paragraph and give [] an M parameter:



>> string[5,10]
=> "is a cool"
You can also use a Range object as an argument:



>> string[7..14]
=> "a Cool"
>> String[-12..-3]
=> "Ol Languag"
>> string[-12..20]
=> "Ol Langua"
>> String[15..-1]
=> "Language."
You can also directly give the content of the substring you want to get, if you find it, return to the string, do not find the return nil:



>> string[' Cool Lang ']
=> "Cool Lang"
>> string[' very cool Lang ']
=> Nil
Regular expression:



>> String[/c[ol]+/]
=> "Cool L"
Slice and slice!:



>> string.slice! (' Cool ')
=> "Cool"
>> string
=> "Ruby is a language."
[The]= method can set the found string:



>> string = ' Ruby is a cool language. '
=> "Ruby is a cool language."
>> string[' cool ' = ' great '
=> "Great"
>> string
=> "Ruby is a great language."
>> string[-1] = '! '
=> "!"
>> string
=> "Ruby is a great language!"
>> string[-9..-1] = ' thing to learn '
=> "thing to learn"
>> string
=> "Ruby is a great thing to learn"
Merging strings



>> ' a ' + ' B '
=> "AB"
>> ' a ' + ' B ' + ' C '
=> "ABC"
+ will always get a new string, so try again:



>> str = ' Hi '
=> "HI"
>> str + ' there. '
=> "Hi there."
>> Str
=> "HI"
Try the << method again, it will change the original string:



>> str = ' Hi '
=> "HI"
>> str << ' there. '
=> "Hi there."
>> Str
=> "Hi there."
Merging strings by interpolation



>> str = ' Hi '
=> "HI"
>> "#{str} there."
=> "Hi there."
Interpolation can be any Ruby expression:



>> "The sum is #{2+2}"
=> "The sum is 4"
No, try this again:



>> ' My name is #{
>> class Person
>> Attr_accessor:name
>> End
>> d = person.new
>> d.name = ' David '
>> D.name
>>}. "
=> "My name is David."
A better way: Ruby will call the object's To_s method in interpolation, you can define your own to_s method:



>> class Person
>> Attr_accessor:name
>> def to_s
>> Name
>> End
>> End
=>: to_s
>> David = Person.new
=> #<person:0x007fbde8a195c0>
>> david.name = ' David '
=> "David"
>> "Hello, #{david}!"
=> "Hello, david!"
In the example above, we take David as a interpolation, and the result is that it will call its to_s.



Query string



There are several flavors of the query string, some can give you a response to Boolean values, and some give you a status report of the string in its current state.



Boolean



You can ask if the string contains a substring, use include? , try:



>> string = ' Ruby is a cool language. '
=> "Ruby is a cool language."
>> string.include? (' Ruby ')
=> true
>> string.include? (' Chinese Version ')
=> false
Start: Start_with?, end: End_with?, try again:



>> String.start_with? (' Ruby ')
=> true
>> String.end_with? ("!!!")
=> false
Ask if the string is not in:



>> String.Empty?
=> false
>> "". Empty?
=> true
Content Query



Get the size of the string:



>> string.size
=> 24
Or:



>> String.Length
=> 24
See how many times the specified character appears in the string:



>> string.count (' a ')
=> 3
How many times a range of characters has occurred altogether:



>> string.count (' g-m ')
=> 5
Because it is case sensitive, try again:



>> String.count (' A-Z ')
=> 1
Try this again:



>> string.count (' Aey. ')
=> 10
There are also negative forms, which use ^:



>> string.count (' ^aey. ')
=> 14
>> string.count (' ^g-m ')
=> 19
Change a pattern:



>> string.count (' ag-m ')
=> 8
>> string.count (' ag-m ', ' ^1 ')
=> 8
Query characters in the string index, use index, reverse check, use Rindex:



>> string.index (' cool ')
=> 10
>> string.index (' l ')
=> 13
>> string.rindex (' l ')
=> 15
Use the Ord method to get the ordinal encoding of a character:



>> ' a '. Ord
=> 97
Multiple characters, take only the first character:



>> ' abc '. Ord
=> 97
Turn:



>> 97.CHR
=> "a"
9:46 * * *



String comparisons and order



2016-09-12 08:09 * * *



The String class mixes the comparable module, which defines the <=> method. So you can do this:



>> ' A ' <=> ' B '
=>-1
>> ' B ' > ' A '
=> true
>> ' A ' > ' a '
=> true
>> '. ' > ', '
=> true
The <=> method returns 1 when the object on the right is large, returns 1 when the object is large on the left, and returns 0 when the two objects are equal.



' B ' is greater than ' a ', ' a ' is greater than ' a ', the effect of the order is the character value, ' A ' is a, ' a ' is 65. '. ' is 46, ', ' is 44.



Comparison is equal



The most common method is = =, try:



>> ' string ' = = ' string '
=> true
>> ' string ' = ' house '
=> false
Two ' string ' are different objects, but their contents are the same.



String#eql? Method can also test for equality. It's usually the same as = =. and string#equal? , it is generally compared to two objects that are not the same object.



>> ' a ' = = ' a '
=> true
>> ' a '. eql? (' a ')
=> true
>> ' a '. Equal? (' a ')
=> false
String distortion



String deformation is divided into three main categories: case, format, content distortion.



Case



Try these:



>> string = ' I Love You '
=> "I Love You"
>> String.upcase
=> "I Love You"
>> String.downcase
=> "I Love You"
>> String.swapcase
=> "I Love You"
First Letter Capital Capitalize/capitalize! :



>> string = ' I love You '
=> "I Love You"
>> string.capitalize
=> "I Love You"
Formatting



The Rjust,ljust method can adjust the size of a string:



>> string = ' I Love You '
=> "I Love You"
>> String.rjust (25)
=> "I Love You"
>> String.ljust (25)
=> "I Love You"
Provide a second parameter to the method:



>> String.rjust (25, '. ')
=> "......... I Love You "
>> String.ljust (25, '-')
=> "I Love You---------------"
Try the Center method:



>> String.center (25, ' * ')
=> "*******i Love you********"
Remove whitespace using the Stip,lstrip,rstrip method:



>> string = ' I Love You '
=> "I Love You"
>> String.strip
=> "I Love You"
>> String.lstrip
=> "I Love You"
>> String.rstrip
=> "I Love You"
Content Distortion



Chop and Chomp methods can erase the end of a string. Chop is an unconditional deletion character, chomp if the directory substring is found at the end, it is deleted. The default chomp is a newline character.



Try:



>> "I Love You". Chop
=> "I Love Yo"
>> "I Love you\n". Chomp
=> "I Love You"
>> "I Love You". Chomp ("U")
=> "I Love Yo"
Try the power of clear:



>> string = "I Love You"
=> "I Love You"
>> String.clear
=> ""
>> string
=> ""
Replace:



>> string = "I ..."
=> "I ..."
>> string.replace ("I Love You")
=> "I Love You"
>> string
=> "I Love You"
Delete, the rule of the parameter is the same as the parameter rule of the Count method:



>> "I Love You". Delete ("Oue")
=> "I Lv Y"
>> "I Love You". Delete ("^o")
=> "Oo"
>> "I Love You". Delete ("A-e", "^c")
=> "I Lov You"
Crypt,des data encryption, its only parameter is a two-digit salt character:



>> "I Love You". Crypt ("34")
=> "342C1RO5Q3YLQ"
Succ



>> "a". succ
=> "B"
>> "abc". SUCC
=> "Abd"
>> "Azz". succ
=> "Baa"
String conversions



The argument is a number in the range 2-36.



>> "To_i" (17)
=> 289
Do not quite understand the meaning of the parameters of the To_i method, is not the parameter represents the number of digits, the system? Base 17? Base 8,base 16, do not know what the meaning of the system.
8-bit: oct,16 bit: Hex



>> "Oct"
=> 64
>> "Hex".
=> 256
To_f, convert to floating-point number, to_s, return receiver, To_sym,intern, convert to symbol.



>> "1.2345". To_f
=> 1.2345
>> "Hello". to_s
=> "Hello"
>> "abc". To_sym
=>: ABC
>> "1.23and some words". To_f
=> 1.23
>> "Just some words". to_i
=> 0
String encoding



Encoding of source files



The default is UTF-8 encoding. To be sure, put the following code in a file and run it again.



Puts __encoding__
To change the encoding of the source file, you can use a magic annotation at the top of the file:



# encoding:encoding
For example, set into Us-ascii:



# ENCODING:ASCII
Encoding of individual strings



>> str = "Test string"
=> "Test String"
>> str.encoding
=> #<encoding:utf-8>
Set string encoding:



>> Str.encode ("Us-ascii")
=> "Test String"
Symbol



The symbol is an instance of Ruby's built-in class symbol. Their literal constructors are preceded by a colon:



: A
: Book
: "Here's how to make a symbol with spaces in it."
To create a symbol by using the To_sym method:



>> "a". To_sym
=>: A
>> "coverting string to symbol with intern ...". Intern
=>: "coverting string to symbol with intern ..."
Convert a symbol to a string:



>>: a.to_s
=> "a"
>>
The main features of the symbol



Symbols are like strings, many times like integers. The main features are: invariance and uniqueness.



Invariance



A symbol cannot be changed as long as it exists.



Uniqueness



You see a symbol: ABC, no matter where you see it, it is the same object.



Do an experiment:



>> "abc". object_id
=> 70179527234100
>> "abc". object_id
=> 70179527221160
>>: abc.object_id
=> 70179535013580
>>: abc.object_id
=> 70179535013580
Symbols and identifiers



The following code contains a symbol object: x, and a local variable identifier s:



s =: X
Ruby's interior uses symbols to track the names of all the variables, methods, and constants that it creates. Check this out:



>> Symbol.all_symbols
=> [: Inspect,: Intern,: object_id, const_missing,: method_missing,
: method_added,: singleton_method_added,: method_removed,
: Singleton_method_removed,
Assign a value to a variable or constant, create a class, or write a method, and the identifier you select will be placed by Ruby in its symbol table. We can verify:



>> Symbol.all_symbols.size
=> 3481
>> ABC = 1
=> 1
>> Symbol.all_symbols.size
=> 3481
>> Symbol.all_symbols.grep (/abc/)
=> [: ABC]
Use of symbols



The most commonly used is the parameter of the method and the hash key.



Symbols as Method parameters



Attr_accessor:name
Attr_reader:age
The Send method can send a message without a point, and it can receive a symbol:



"ABC". Send (: upcase)
Send can also receive a string parameter, such as UpCase. But by giving it a symbol directly, you save Ruby's business, or Ruby converts the string into a symbol internally.



Symbol as hash key



>> M_hash = {: Title => "Beautiful Life": Year => 1997}
=> {:title=> "Beautiful Life",: year=>1997}
>> M_hash[:year]
=> 1997
Roughly the hash, using the string key:



>> M_hash = {"title" => "Beautiful Life", "Year" => 1997}
=> {"title" => "Beautiful Life", "Year" =>1997}
>> m_hash["title"]
=> "Beautiful Life"
The symbol is quicker and looks better as a hash key.



Here's the hash:



has = {: Title => "Beautiful Life": Year => 1997}
Can also be written as:



has = {title: "Beautiful Life", year:1997}
Comparison of strings and symbols



Think of symbols as integers that look like strings.



Numeric objects



In Ruby, numbers are also objects, and you can send messages to them:



>> n = 99.6
=> 99.6
>> m = N.round
=> 100
>> puts M
100
=> Nil
>> x = 12
=> 12
>> if X.zero?
>> puts "x is zero"
>> Else
?> puts "x is not zero"
>> End
X is not zero
=> Nil
Number class



Numeric
Float
Integer
Fixnum
Bignum
Arithmetic



>> 1 + 1
=> 2
>> 10/5
=> 2
>> 16/5
=> 3
>> 10/3.3
=> 3.0303030303030303
>> 1.2 + 3.4
=> 4.6
>> -12--7
=>-5
>> 10% 3
=> 1
hexadecimal integer preceded by 0x:



>> 0x12
=> 18
>> 0x12 + 12
=> 30
The front band 0 is a octal integer:



>> 012
=> 10
>> 012 + 12
=> 22
>> 012 + 0x12
=> 28
Most arithmetic operations are actually methods, because there are grammatical sugars so it looks like an operator, which should have been:



>> 1.+ (1)
=> 2
>> 12./(3)
=> 4
>> -12.-(-7)
=>-5
Time and date



Import Date:



>> require ' date '
=> true
>> date.parse ("April 1705"). England.strftime ("%B%d%Y")
=> "April 13 1705"
There are several classes of processing time and date: Time,date,datetime. Their objects can be called Date/time objects. Use them first to import:



Require ' date '
Require ' time '
The first line provides Date and DateTime classes, and the second line is the time class. In the future, you might combine the classes of date and time together.



Instantiating a Date/time object



Create a Date Object



>> today = Date.today
=> #<date:2016-09-12 ((2457644j,0s,0n), +0s,2299161j) >
>> today.to_s
=> "2016-09-12"
>> puts today
2016-09-12
=> Nil
Use Date.new to create a Date object to provide it with years, months, days:



>> puts Date.new (1959,2,1)
1959-02-01
If you do not provide month and day, the default will be 1.



To create a Date object with parse:



>> puts Date.parse ("2012/7/22")
2012-07-22
>> puts Date.parse ("03/6/9")
2003-06-09
>> puts Date.parse ("33/6/9")
2033-06-09
>> puts Date.parse ("77/6/9")
1977-06-09
>> puts Date.parse ("November 2 2013")
2013-11-02
>> puts Date.parse ("Nov 2 2013")
2013-11-02
>> puts Date.parse ("2 Nov 2013")
2013-11-02
>> puts Date.parse ("2013/11/2")
2013-11-02
Create a Time object



Create Time object: New (also called Now), at,local (also called mktime), parse.



>> time.new
=> 2016-09-12 10:47:31 +0800
>> time.at (100000000)
=> 1973-03-03 17:46:40 +0800
>> Time.mktime (2007,10,3,14,3,6)
=> 2007-10-03 14:03:06 +0800
>> require ' time '
=> false
>> Time.parse ("March, 1985, 10:35 PM")
=> 1985-03-22 22:35:00 +0800
Epoch (midnight on January 1, 1970, GMT)
Creating Date/time Objects



DateTime is a subclass of Date.



>> puts Datetime.new (2009, 1, 2, 3, 4, 5)
2009-01-02t03:04:05+00:00
=> Nil
>> puts DateTime.Now
2016-09-12t10:54:22+08:00
=> Nil
>> puts DateTime.Parse ("October, 1973, 10:34 AM")
1973-10-23t10:34:00+00:00
=> Nil
JD (Julian date), Commercial,strptime
Date/time Query method



>> dt = DateTime.Now
=> #<datetime:2016-09-12t10:57:55+08:00 ((2457644j,10675s,478039000n), +28800s,2299161j) >
>> Dt.year
=> 2016
>> Dt.hour
=> 10
>> Dt.minute
=> 57
>> Dt.second
=> 55
>> T = Time.now
=> 2016-09-12 10:58:12 +0800
>> T.month
=> 9
>> t.sec
=> 12
>> d = date.today
=> #<date:2016-09-12 ((2457644j,0s,0n), +0s,2299161j) >
>> D.day
=> 12
What's the date of the week?



>> d.monday?
=> true
>> d.friday?
=> false
Date/time Method of formatting



All Date/time objects have strftime methods.



>> T = Time.now
=> 2016-09-12 11:08:22 +0800
>> t.strftime ("%y-%m-%d")
=> "16-09-12"
>> t.strftime ("%y-%m-%d")
=> "2016-09-12"
%Y: four-digit years
%y: two-digit years
%B,%B: Short month, long month
%M: Digital Month
%d: day, left with 0
%e: Day
%a,%a: Short day name, Long day name
%h,%i: Hour, 24, 12.
%m: Min
%s: sec
%c:%a%b%d%h:%m:%s%Y
%x:%m/%d/%y
RFC 2822 (email), RFC 2616 (HTTP):



>> Date.today.rfc2822
=> "Mon, Sep 2016 00:00:00 +0000"
>> DateTime.now.httpdate
=> "Mon, Sep 2016 03:15:24 GMT"
Date/time Conversion method



Time has To_date, To_datetime method, date has To_time,to_datetime method, DateTime has To_time,to_date method.



Date/time arithmetic



>> T = Time.now
=> 2016-09-12 11:18:29 +0800
>> t-20
=> 2016-09-12 11:18:09 +0800
>> T + 20
=> 2016-09-12 11:18:49 +0800
Conversion of the Month:



>> dt = DateTime.Now
=> #<datetime:2016-09-12t11:19:25+08:00 ((2457644j,11965s,940690000n), +28800s,2299161j) >
>> puts DT + 100
2016-12-21t11:19:25+08:00
=> Nil
>> puts DT >> 3
2016-12-12t11:19:25+08:00
=> Nil
>> puts DT << 10
2015-11-12t11:19:25+08:00
=> Nil
Days:



>> d = date.today
=> #<date:2016-09-12 ((2457644j,0s,0n), +0s,2299161j) >
>> puts D.next
2016-09-13
=> Nil
>> puts D.next_year
2017-09-12
=> Nil
>> puts D.next_month
2016-10-12
=> Nil
>> puts D.prev_day (10)
2016-09-02
=> Nil
Upto,downto:



>> d = date.today
=> #<date:2016-09-12 ((2457644j,0s,0n), +0s,2299161j) >
>> Next_week = d + 7
=> #<date:2016-09-19 ((2457651j,0s,0n), +0s,2299161j) >
>> D.upto (Next_week) {|date| puts "#{date} is a #{date.strftime ("%A ")}"}
2016-09-12 is a Monday
2016-09-13 is a Tuesday
2016-09-14 is a Wednesday
2016-09-15 is a Thursday
2016-09-16 is a Friday
2016-09-17 is a Saturday
2016-09-18 is a Sunday
2016-09-19 is a Monday
=> #<date:2016-09-12 ((2457644j,0s,0n), +0s,2299161j) >
View Help: Ri Date



11:24 * * * *


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.