加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby流程控制语句

发布时间:2020-12-17 04:11:20 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #coding=utf-8=begin通过这个例子进一步学习ruby中的数据类型以及循环分支等控制语句的用法=endclass Example02 #输入数据判断数据类型:numeric,stri

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#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)

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读