Ruby learning notes (1) first-time Grammar

Source: Internet
Author: User

From the technical point of view, ruby itself is really great, making the work of programmers easy and interesting!
The following code demonstrates how to find a prime number within 100:
Copy codeThe Code is as follows:
Using System;
Namespace Mersenne
{
Class Program
{
Static void Main (string [] args)
{
For (int I = 2; I <50; I ++)
{
If (CheckDigital (I ))
{
Console. WriteLine ("{0}", I );
}
}
Console. ReadLine ();
}
Static bool CheckDigital (int I)
{
If (I <= 1) {return false ;}
If (I = 2) {return true ;}
Bool _ result = true;
For (int j = 2; j <I; j ++)
{
If (I % j = 0)
{
_ Result = false;
Break;
}
}
Return _ result;
}
}
}

Refer to this idea and translate it into ruby:
Copy codeThe Code is as follows:
For I in 2 .. 100
Flag = true;
For j in 2... I
If I % j = 0
Flag = false;
Break;
End
End
If flag
Print I, "\ n"
End
End

The flexibility of ruby syntax can be reduced to the following code:
Copy codeThe Code is as follows:
For I in 2 .. 100
Flag = true;
(2 .. I). each {| n | flag = false if I % n = 0}
Print I, "\ n" if flag
End

You can also write it as follows:
Copy codeThe Code is as follows:
Def checkNum? (Num)
Return true if num = 2
F = true;
For j in 2... num
If num % j = 0
F = false;
Break
End
End
Return f
End

(2 .. 50). each {| x | print x, "\ n" if checkNum? (X )}
Another implementation:
Copy codeThe Code is as follows:
$ Arr = [] # defines a global array to save calculation results.
$ Arr [0] = 2
# Definition method: add the odd prime numbers within n to $ arr (the odd prime numbers must be at the same time, except for 2)
Def add_prime (n)
3. step (n, 2) {| num | $ arr <num if is_prime? Num}
End
# Define the method to determine whether it is a prime number
Def is_prime? (Number)
J = 0
While $ arr [j] * $ arr [j] <= number
Return false if number % $ arr [j] = 0
J + = 1
End
Return true
End
Add_prime (50); # Call
Puts $ arr. join (',') # output result

Author: Yang Guo under the bodhi tree

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.