ruby流程控制语句

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#coding=utf-8
=begin
通过这个例子进一步学习ruby中的数据类型
以及循环分支等控制语句的用法
=end
class Example02
 #输入数据判断数据类型:numeric,string,array,hash,boolean,nil....
 def judge_obj(x)
    puts "case...when...else"
    puts case x
     when String then "string"
     when Numeric then "numeric"
     when TrueClass,FalseClass then "boolean"
     when NIL then "nil"
     when Array then "array"
     when Hash then "hash"
     else "class"
    
    end
  end
  #while循环:输入数字进行遍历
  def loop_while(x)
   puts "while loop"
    while x>=0 do
      puts x
      x=x-1
    end
  end 
  #until循环
  def loop_until(x)
     puts "until loop"
      until x>10 do
        puts x
        x=x+1
      end
   end
   #for循环
   def loop_for(x)
    puts "for loop"  
   
    for element in x
      puts element
    end
   
   end
   #for循环遍历hash
    def loop_for_hash(x)
      puts "for hash loop"  
      for key,value in x
        puts "#{key}=>#{value}"
      end
     end
   #输入一个数字,并迭代
     def iterator_numeric(x) 
       puts "iterator x="+x.to_s()
       x.times{|y|print y}
         puts
     end
   #遍历一个数字区间
     def upto_numeric(x,y)
       puts "upto x="+x.to_s()+" to y="+y.to_s()
       x.upto(y){|x| print x}
     end
  
end

e2=Example02.new()
e2.judge_obj(1)
e2.judge_obj(1.0)
e2.judge_obj(1.0.class)
e2.judge_obj(1==1)
e2.judge_obj("这是字符串")
arry=[1,2,3]
e2.judge_obj(arry)
numbers = Hash.new()
numbers["one"]=1
numbers["two"]=2
numbers["three"]=3
e2.judge_obj(numbers)
e2.loop_while(10)
e2.loop_until(5)

e2.loop_for(arry)
hash={:a=>1,:b=>2,:c=>3}
e2.loop_for_hash(numbers)
e2.iterator_numeric(9)
e2.upto_numeric(4,6)