常用基础备忘

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

#coding:utf-8
#熟悉ruby基本数据类型


class Ruby01
  puts "基本数字类型"
  puts 1
  puts 1.0
  puts 1.class #输出Fixnum
  puts 1.0.class #输出Float
  puts 1.0.class.class #输出Class
  
  puts 
  puts "算数基本操作"
  puts 4/2
  puts 4/2.0
  puts 4.0/2.0
  puts 4*2
  puts 4**2
  puts 4%2
  
  puts 
  puts "文本"
  puts '这是第一个ruby程序'\
  '使用单引号可以跨越多行'
  puts "双引号使用"
  puts "4/2=#{4/2}" #双引号中可以使用变量和表达式,单引号下不行,会当做字符串输出
  puts "圆周率是%.4f"%Math::PI #相当于 printf"圆周率是%.4f"%Math::PI 
  
  puts 
  puts "访问字符串和子字符串"
  s="hello"
  puts s[0]  
  puts s[s.length()-1]
  puts s[-1]
  puts s[-2]
  puts s[-s.length()]
  puts s[s.length()]
  puts s[s.length()].class #输出NilClass
  
  puts 
  puts s[0,3]
  puts s[-3,5]
  puts s[0,-2].class
  puts s[2..4]
    
  
  puts 
  s[s.length(),0]="world"
  puts s
  s[5,0]=","
  puts s
  s[5,5]=""
  puts s
  
  puts
  s="字符串迭代"
  puts s 
  s.each_char{|x| print"#{x}-"}
  
  #数组    
=begin
   ruby中数组用逗号分割元素
    数组下标从0开始
   []数组长度为0
   each方法可以遍历一个数组
=end
  puts
  puts "数组"
  arr =[1,2,3];arr.each{ |x|print"#{x},"};
  puts 
  arr =[-10...0,0..10,]
  puts "arr数组第一个元素为数组";arr[0].each{|x|print"#{x},"};
  puts "arr数组第二个元素为数组";arr[1].each{|x|print"#{x}-"};
 
  
    
  puts
  puts "数组创建"
  puts "empty=Array.new():#{Array.new()}"
  puts "nils=Array.new(3):#{Array.new(3)}"
  puts "0=Array.new(4,0):#{Array.new(4,0)}"
  puts "copy=Array.new(nils):#{Array.new(arr)}" #数组拷贝
  puts "count =Array.new(3):#{Array.new(3){|x| x+1}}" #元素索引填充数组
  
  
      
  puts 
  puts "数组运算"
=begin
   ruby中是可变数组
   >>可以给数组添加数据
   >>可以添加多条数据
   |取合集
   &取交集
=end
  arr0=[]
  arr0<<1 
  arr0<<2<<3
  
  puts "#{arr0}"
  arr0<<[4,5,6]
  puts "#{arr0}"
  arr1=[1,3,2,5,4]
  arr2 =[2,3]
  puts "取并集:{arr1 | arr2}-->#{arr1|arr2}"
  puts "取并集:{arr2 | arr1}-->#{arr2|arr1}"
  puts "取交集:{arr1 & arr2}-->#{arr1&arr2}"
  puts "取交集:{arr2 & arr1}-->#{arr2&arr1}"
  
  #对象
=begin
  equal比较对象
  eql比较对象值
  ==比较值
  |取合集
  &取交集
  object_id用来比较是否是同一个对象
   
=end
  puts
  puts "对象比较"
  obj1="ruby"
  obj2=obj3="ruby"
  
  puts obj1.equal?(obj2)
  puts obj2.equal?(obj3)
  puts obj1.eql?(obj2)
  puts obj2.eql?(obj3)
  puts "obj1的obj1.object_id=#{obj1.object_id},obj2的obj2.object_id=#{obj2.object_id},obj3的obj3.object_id=#{obj3.object_id}"
  puts 1==1.0 #==比较,可以进行值转换
  puts 1.eql?(1.0) #eql比较,不能进行值转换
  puts "0==nil:#{0==nil}"#判断是否为nil 另一种方法0.nil?
=begin
  to_i,to_f,to_s用来转换成Integer,Float,string类型
=end
  puts 
  puts "类型转换"
  s1=1
  puts "s1是:#{s1.class}"
  s2="1"
  puts "s2是:#{s2.class}"
  s3=1.0
  puts "s3是:#{s3.class}"
  s4=s1.to_s()
  puts "s4是:#{s4.class}"
  s5=s2.to_i()
  puts "s5是:#{s5.class}"
  puts "s2==s4:#{s2==s4}"
  puts "s1==s5:#{s1==s5}"
  
  
  

end
#new()创建对象
e =Example01.new();

print e