Ruby基础知识-Ruby的数据类型

Ruby 数据类型有数字,字符串,数组,哈希表,区间,正则表达式。
数字分为整数型(1,0,75 ,1e3),浮点型(2.4 ,7.0 ,0.99)。浮点型数据小数点后必须跟数字( 1.e3 不可以,1.1e3可以)。数字可以有前缀:0表示八进制, 0x表示十六进制, 0b表示二进制(0724,0x5AC4,0b11101)。
字符串是在‘ ’(单引号)、 “ ”(双引号)之间的代码。

数组的下标从0开始。Ruby的数组和其它语言不同,数组的每个元素可以是不同的类型:[ 2.4, 99,“thank you”,[ a, b ,c ] ,78 ]。



我们来看下几个数组的小列子

demo1:

arr1=[]
arr2=Array.new
arr3=['4','5','6']

print arr1,"\n"
print arr2,"\n"
print arr3,"\n"

分别返回

irb(main):010:0> print arr1,"\n"

=> nil
irb(main):011:0> print arr2,"\n"

=> nil
irb(main):012:0> print arr3,"\n"
456
=> nil


demo2:

arr = ['3','4','5','6','7','8','9']

puts "aaaa",arr[0]
puts arr.first
puts arr[arr.length-1]
puts arr[arr.size-1]
puts arr.last
puts arr[-1]
puts arr[-8]

print arr[1..3]
print arr[-3,2]

#数组的索引从0开始,一直到数组的长度减去1;负数表示从数组末尾开始的索引;用一对数字来索引数组,第一个数字表示开始位置,第二数字表示从开始位置起的元素数目。

demo3:

arr=[4,5,6]
print arr.join(","),"\n"

arr[4]="m";#赋值
print arr.join(","),"\n" #4,5,6,,m

print arr[3],"\n"; #nil

arr.delete_at(3) #删除索引3的位置

print arr.join(","),"\n" # 4,5,6,m

arr[2]=["a","b","c"] 

print arr.join(","),"\n" #4,5,a,b,c,m

print arr[2],"\n" #打印2号的位置元素 abc

arr[0..1]=[7,"h","b"] #把0..1 号元素替换为7,"h","b"

print arr.join(","),"\n" #7,h,b,a,b,c,m

arr.push("b");
print arr.join(","),"\n" #7,h,b,a,b,c,m,b

arr.delete(["a","b","c"]) #删除元素["a","b","c"]

print arr.join(","),"\n"

arr.delete("b")

print arr.join(","),"\n" #7,h,m

arr.insert(3,"d")
print arr.join(","),"\n"

arr<<"f"<<2
print arr.join(","),"\n" #向数组尾部添加元素

arr.pop #删除尾元素

print arr.join(","),"\n"
arr.shift #删除首元素

print arr.join(","),"\n"












demo4:

aaaa = ["aa",4,5,"bb"]
bbbb = [4,1,3,2,5]

print aaaa+bbbb  , "\n"  #aa45bb41325

print aaaa*2  ,"\n"	#aa45bbaa45bb

print bbbb-aaaa , "\n"	#132

# "并运算,交运算"

print aaaa | bbbb  ,"\n" #aa 45 bb 132

print aaaa & bbbb  ,"\n"

# "排序,倒置"

print bbbb.sort   ,"\n"

print aaaa.reverse  ,"\n"



你可能感兴趣的:(ruby,ruby)