Ruby condition control structure

Source: Internet
Author: User

 

I. Comparison statements

Most of them are the same as other languages. Note <=>,

 

Condition Statement

The following forms

  • If
  • If... else... end
  • If... elsif... else... end
  • Unless (if not)
  • Case... when
x=1if x==1    puts 1elsif x==2    puts 2else     puts  3end

Note that elsif is not elseif. Compared with C, an end is added..

 

However, the case statement of Ruby differs greatly from the C/C ++ format:

Case when the judgment item when comparison value then code else code end
    def [](index)        case index            when 0, -2 then @x            when 1,-1  then @y            when :x,"x" then @x            when :y,"y" then @y            else nil        end    end

P [0], p [-2] returns x

For example, the following two sections of code are equivalent, but the code using case is clearer:

if var < 60  print "failed/n"elsif var < 70  print "passed/n"elsif var < 80  print "good/n"elsif var < 90  print "great/n"else  print "excellent/n"endcase var  when 0..59 then print "failed/n"  when 60..69 then print "passed/n"  when 70..79 then print "good/n"  when 80..89 then print "great/n"  else print "excellent/n"end

 

Loop iteration statement

X. Times

 

X. updo, X. downto, X. Step (limit, steplength)

 

: Loop statement

Loop

Break jumps out of the entire Loop

Http://www.cnblogs.com/cnblogsfans/archive/2009/02/05/1384944.html

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.