Ruby learning notes (1) first-time Grammar

Source: Internet
Author: User

From the technical point of view, Ruby itself is really nice.ProgramThe work of Members becomes easy and interesting!
The followingCodeDemonstrate how to find a prime number less than 100:

Copy code The 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 the calculation result.
$ 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.