ruby流程控制语句

代码] [Ruby]代码

#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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值