Ruby's Basic grammar learning summary _ruby topics

Source: Internet
Author: User

1.Keyword

Keywords cannot be used to define variables or constants, module, class, def, undef, defined ?, if, then, else, elsif, case, when, unless, for, in, while, until, next, break, do, redo Retry yield yield not true and false

Notes

Single-line comments begin with #, such as: #This is a comment statement
Multi-line comments begin with = begin and end with = end, such as:
Copy the code:

= begin
block_test = lambda {puts 'This is from lambda!'}
def block_foo (bt)
 puts 'Before yield!'
 bt.call
 puts 'After yield!'
end
block_foo (block_test)
= end
Data type

The following data types in Ruby: Numeric (including Fixnum and Float), String, Boolean, Array, Regexp, Range, Hash, and a special type: Symbol

4.Assignment and conditional operations

Use "=" for assignment in Ruby for batch assignment, such as a, b, c = 1,2,3
Conditional operations in Ruby, as follows:

Operator Description
== and! = Compares whether the values of two objects are equal, a = 1, b = 1.0, a == b (true)
eql? compares whether the values of two objects are equal and the data type is the same, a = 1, b = 1.0, a.eql? b (false, a is a Fixnum type, b is a Float type)
eqlal? Compares whether the addresses of two objects in memory are the same, a = 1, b = 1, a.eqlal? b (false, 2 objects in memory, the addresses are different), a = 1, b = a , a.eqlal? b (true)
<=> Compare the size of the values of two objects, correspondingly return 1 (greater than), 0 (equal), -1 (less than)
>,> =, <=, <Compare the values of two objects, returning true and false
=== The interval contains a relational operator, whether the right object is within the range of the left interval
= ~ And! ~ Regular expression matching operator, which means match and mismatch regular expressions
5.Output and input

The built-in IO input and output methods in the Ruby language are written in the Kernel module, and Mix-in is in the root class Object, and the input and output methods are used in any class, which can be called directly.
Example output method code:
Copy the code:

print 'Hello!' #Output: Hello!
print "Hello! \ n" #Output: Hello!
printf 'Number:% .2f, String:% s', 14.547, 'hi!' #Output: Number: 14.55, String: hi!
print "\ n"
puts 'Hello!' 'hi' #Output: Hello! hi
puts 'Hello!', 'hi' #Output: Hello! [line feed] hi
print can add parameters to output to the file, the default output to the console, printf is output according to the format, as in the above code,% .2f means that the first parameter is output as a Float type, leaving 2 decimal places,% s is the second Each value is output as a String. The difference between print "Hello! \ N" and print 'Hello \ n' is that the "" number parses the output content, \ n functions as a newline, and the "" number outputs the content as is. The output is as-is, without line breaks. The parameters of the puts method are variable parameters, which can have zero or more parameters. The spaces between the parameters are output without line breaks. The parameters are separated by ",", and each output line breaks;

Input method, gets is used to receive the user-entered string, a newline character is automatically added at the end of the string, so when using the gets method to obtain input data, the chomp method is used to remove the newline character at the same time

Copy the code:

STDOUT.flush
in_data = gets.chomp
6. Judgment of conditions

The condition judgment can be performed using if else, unless, and case. Using different keywords in different situations can make the code more concise and easy to understand. The following example code:
Copy the code:

r = rand * 100
rf = format ('%. 2f', r)
#Common writing
if r> 50 then puts "score: # {rf}" end
# Better writing
puts "Score: # {rf}" if r> 50
#When judging if not, use unless, the next code is equivalent to the previous code
puts "Score: # {rf}" unless r <= 50
# Multi-conditional judgment
if r <50
 puts "Score: # {rf} Grade: Failed"
else
 puts "Score: # {rf} Grade: Good"
end
#More conditions
if r> 90
 puts "score: # {rf} achievement: excellent"
elsif r> 70
 puts "Score: # {rf} Grade: Good"
elsif r> 50
 puts "Score: # {rf} Grade: Pass"
else
 puts "Score: # {rf} Grade: Failed"
end
#Better way, use case branch statements, the conditions behind when use Range, Ruby automatically uses === for judgment
case r
when 90..100
 puts "score: # {rf} achievement: excellent"
when 70..90
 puts "Score: # {rf} Grade: Good"
when 50..70
 puts "Score: # {rf} Grade: Pass"
else
 puts "Score: # {rf} Grade: Failed"
end
7.Circulation

Ruby's loop functions are quite powerful. In addition to the general while, until, and for loops, there are also each, times, upto, downto, step, etc. It is very convenient to use different looping methods for different loop objects. The example code is as follows:

Copy the code:

i = 0
#Plain while loop
while i <10
 i + = 1
 puts i
end
#Single sentence code while loop
puts i + = 1 while i <10
#Until loop of single sentence code, until == while not
puts i + = 1 until i == 10
j = 10..20
#Use for for a full loop of objects. Objects can be in the form of collections such as arrays, ranges, and maps. However, Ruby officially does not recommend using for loops too much. You can use each instead, because for loops do not have new scopes. Variables can be accessed outside the loop, such as the variable t in the side loop, which can be accessed outside the for loop
for t in j
 puts t
 break if t == 17 #When the loop reaches t equal to 17, jump out of the entire loop
end
#Better way: use each to traverse
#Single line code block using {}
j.each {| e | puts e}
# Multi-line code block using do end
j.each do | e |
 next if e == 17 #Escape from this loop when e is 17
 puts e
end
#A predetermined number of loops, you can use times
5.times {| e | puts e} #e values start from 0
#Permutations with order can be traversed using upto or downto
'a'.upto (' z ') {| e | puts e unless (' h '..' n ') === e} #Iterate through English characters between az when e is not a letter between hn , Output
9.downto (1) do | e |
 print "Square value of # {e}: # {e ** 2}, power of # {e}: # {e ** 3}"
 puts
end
#Incremental loops with the same step size can use step
1.step (100,3) {| e | puts e}


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.