基本数据类型和对象

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

# coding: utf-8
#Example01:学习数据类型和对象
#@author yongtree
class Example01
  #基本的数字类型,和java差不多,但是不同的是都是对象
  puts "基本数字类型"
  puts 1
  puts 1.0
  puts 1.class
  puts 1.0.class

  #基本算数操作
  puts
  puts "基本算数操作"
  puts 4/2
  puts 4/2.0
  puts 4%2
  puts 4+2
  puts 4*2
  puts 4**2

  #文本
  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].class #返回nil

  puts
  puts s[0,3]
  puts s[-3,5]  #-3-->0
  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}-"}

  #数组
  puts
  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
  puts "arr第二个元素为数组,打印:";arr[1].each { |x| print "#{x},"};
  puts
  puts
  puts "数组创建"
  puts "empty=Array.new:#{Array.new}"
  puts "nils=Array.new:#{Array.new(3)}"
  puts "zeros=Array.new:#{Array.new(4,0)}"
  puts "copy=Array.new:#{Array.new(arr)}"
  puts "count=Array.new:#{Array.new(3){|x| x+1}}"

  puts
  puts "数组运算"
  arr0=[]
  arr0<<1
  puts "#{arr0}"
  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}"

  #对象
  puts
  puts "对象比较"
  obj1="Ruby"
  obj2=obj3="Ruby"
  puts obj1.equal?(obj2) #比较对象  false
  puts obj2.equal?(obj3)             #true
  puts obj1.eql?(obj2)  #比较值    true
  puts obj1==obj2       #比较值   true
  puts "obj1的object_id=#{obj1.object_id},obj2的object_id=#{obj2.object_id},obj3的object_id=#{obj3.object_id}"        #可以通过比较对象的object_id来判断是不是一个对象

  puts 1==1.0      #==比较,值可以转换  true
  puts 1.eql?(1.0) #不能进行值转换      false


end