ruby 数据类型

2018-02-13  本文已影响30人  风___________

1. Ruby 字符串(String)

'这是一个 Ruby 程序的字符串'
puts "你好 #{name1},  #{name2} 在哪?"
# str 实例对象:可以调用任意可用的实例方法
myStr = String.new("THIS IS TEST")
# 字面量特殊语法
%q(this is a string) #same as: 'this is a string'
%Q|this is a string| #same as: "this is a string"

2. Ruby 数组

names = Array.new(20)
names = Array.new(4, "mac")
puts "#{names}"
结果:["mac", "mac", "mac", "mac"]
nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"
结果:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]

digits = Array(0..9)
puts "#{digits}"
结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# each 遍历
# 数组内建方法
Array.[](...) [or] Array[...] [or] [...]
# 字面量特殊语法
words = %w[this is a test] # same as: ['this','is','a','test']
open = %w| { [ < | # same as:  ['{', '[', '<']
white = %W(\s \t \r) # same as:  ["\s", "\t", "\r"]
# %w 开头的遵循单引号引用规则 %W开头遵循双引号引用规则

3. Ruby 哈希

# 空的哈希
months = Hash.new
# 默认值的哈希
months = Hash.new( "month" )
或
months = Hash.new "month"
# 有值的哈希
H = Hash["a" => 100, "b" => 200]
puts "#{H['a']}"
puts "#{H['b']}"
# 字面量特殊语法
numbers = {"one" => 1, "two" => 2}
作为哈希的键 symbol对象比字符串更高效
numbers = {:one => 1, :two => 2}
哈希的内置方法
# 创建 Hash 对象实例
Hash[[key =>|, value]* ] or
 
Hash.new [or] Hash.new(obj) [or]
 
Hash.new { |hash, key| block }

4. Ruby 范围

r = 'a'..'c' # begin <= x <= end
n = 'a'...'c' # begin <= x < end
r.each{|x| p x} # "a" "b" "c"
r.step(2){|x| p x} # "a" "c"

判断是否包含在范围

r = 0...100
r.member? 50 # true
r.include? 100 # false
r.include? 99.9 # true

ruby1.9 cover

triples = 'AAA'.."ZZZ"
triples.include? 'ABC'
triples.cover? 'ABCD'

5. Ruby 符号(symbol)

通过在一个标识符或字符串前面添加冒号的方式表示一个符号字面量

:symbol
:"symbol"
:'another'
s = "string"
sym = :"#{s}"
# 字面量特殊语法-----%s
%s["] #same as: ' " '

反射代码里判断某个对象是否实现方法

# 判断each
o.respond_to? :each
# eg:
> array
 => ["a", "b", "c"] 
> str
 => "thiS iS a String" 
2.3.4 :099 > str.respond_to?:each
 => false 
2.3.4 :100 > array.respond_to?:each
 => true 
2.3.4 :101 > name = :each
 => :each 
2.3.4 :102 > array.respond_to?name
 => true 

str和sym转换

str = "string"
sym = str.to_sym
str = sym.to_s

6. Ruby True False Nil

true false nil 都是对象不是数值
true != 1
都是单键实例
条件判断语句中 任何不同于false和nil的值表现的像true一样包括数字0和1
nil和false表现的一样

7. Ruby 对象

2.3.4 :116 > a=b="ruby"
 => "ruby" 
2.3.4 :117 > c="ruby"
 => "ruby" 
2.3.4 :118 > a.equal?b
 => true 
2.3.4 :119 > a.equal?c
 => false 
2.3.4 :120 > a == b
 => true 
2.3.4 :121 > a == c
 => true 
2.3.4 :122 > a.__id__
 => 70231259959460 
2.3.4 :123 > b.__id__
 => 70231259959460 
2.3.4 :124 > c.__id__
 => 70231259944360 

对象的顺序

2.3.4 :127 > 1<=>5
 => -1 
2.3.4 :128 > 1<=>1
 => 0 
2.3.4 :129 > 5<=>1
 => 1 
2.3.4 :130 > 5<=>"1"
 => nil 
2.3.4 :131 > "1"<=>"2"
 => -1 
上一篇 下一篇

猜你喜欢

热点阅读