Ruby学习笔记之标准库

来源:互联网 发布:centos 安装apache2 编辑:程序博客网 时间:2024/04/29 05:21

标准库


Strings


字符串嵌入表达式

在ruby中,如果在创建字符常量时使用双引号,那么可以在#{}中嵌入一个表达式,Ruby会自动把表达式的值和字符串连接起来

result = "Good night, #{name.capitalize}"

puts "now is #{ def the(a)

'the ' + a

end

the('time')

} for all good coders..."

对于全局变量有不同的语法

$salutation = 'hello' # Define a global variable

"#$salutation world" # Use it in a double-quoted string

调用底层操作系统命令

`date` # => "Mon Apr 13 13:25:58 CDT 2009\n"

`ls`.split[34] # => "ext_c_win32ole.tip"

%x{echo "Hello there"} # => "Hello there\n"

从第二条可以看到,从操作系统返回的结果是一个String,因此还可以程序交互

长字符

Ruby中用%{}来处理长字符。这个字符中可以放任何格式化的字符。

符号(关键字)


可以把符号看做变量名和变量值相同的变量,这时候不分辨变量名和值。由于值和名字都是相同的,因此甚至不用设置初始值,直接用就可以。

符号用在变量不变且仅仅要用来标示的地方。

1.用在映射中

inst_section = {

:cello => 'string',

:clarinet => 'woodwind',

:drum => 'percussion',

:oboe => 'woodwind',

:trumpet => 'brass',

:violin => 'string'

}

inst_section[:oboe] # => "woodwind"

inst_section[:cello] # => "string"

# Note that strings aren't the same as symbols...

inst_section['cello'] # => nil

2.用在全局标示

def walk(direction)

if direction == :north

# ...

end

end

在反射中

由于在Ruby中类中的方法和变量都是用符号来表示的,因此在放射中用的特别多

o.respond_to? :each

集合


Hash


定义

inst_section = {

'cello' => 'string',

'clarinet' => 'woodwind',

'drum' => 'percussion',

'oboe' => 'woodwind',

'trumpet' => 'brass',

'violin' => 'string'

}

在1.9中还支持另一种方法

numbers = { one: 1, two: 2, three: 3 }

这个相当于

numbers = { :one => 1, :two => 2, :three => 3 }

Hash的默认值

可以这样看待hashtable:hashtable中存在每一个查询的键,只是有的键的值为null。这样可以在创建hashtable时指定默认值,每次就可以直接使用默认值(因为null在计算时无用)

if counts.has_key?(next_word)

counts[next_word] += 1

else

counts[next_word] = 1

end

def count_frequency(word_list)

counts = Hash.new(0)

for word in word_list

counts[word] += 1

end

counts

end

可变键

Because strings are mutable but commonly used hash keys, Ruby treats them as a special case and makes private copies of all strings used as keys. This is the only special case,however; you must be very cautious when using any other mutable object as a hash key. Consider making a private copy or calling the freeze method. If you must use mutable hash keys, call the rehash method of the Hash every time you mutate a key

Array


定义

a = [ 1, 'cat', 3.14 ]

添加

a[2] = nil

a<<"ssj"

防问(切片):

a = [ "a", "b", "c", "d", "e" ]

a[2] + a[0] + a[1] #=> "cab"

a[6] #=> nil

a[1, 2] #=> [ "b", "c" ]

a[1..3] #=> [ "b", "c", "d" ]

a[4..7] #=> [ "e" ]

a[6..10] #=> nil

a[-3, 3] #=> [ "c", "d", "e" ]

# special cases

a[5] #=> nil

a[5, 1] #=> []

a[5..10] #=> []

删除元素

delete

有用的方法

clear,清空列表

map和collect,接受一个函数,对列表中的每一个元素作用,得到的是一个新的列表,原来的列表不变

map!和collect!,和map和collect类似,但是改变发生在原来的列表上

select ruby版filter

inject ruby版reduce

对于String的特殊支持

words = %w[this is a test] # Same as: ['this', 'is', 'a', 'test']

open = %w| ( [ { < | # Same as: ['(', '[', '{', '<']

white = %W(\s \t \r \n) # Same as: ["\s", "\t", "\r", "\n"]

Numbers


整型


Ruby的整数在Fixnum和Bignum之间自动转换

迭代

3.times { print "X " }

1.upto(5) {|i| print i, " " }

99.downto(95) {|i| print i, " " }

50.step(80, 5) {|i| print i, " " }

Ranges


作为序列

1..10

'a'..'z'

0..."cat".length

三点没有上界,两点有

区间

(1..10) === 5 # => true

(1..10) === 15 # => false

(1..10) === 3.14159 # => true

('a'..'j') === 'c' # => true

('a'..'j') === 'z' # => false

cold_war.include? birthdate.year

用在case中

case car_age

when 0...1

puts "Mmm.. new car smell"

when 1...3

puts "Nice and new"

when 3...6

puts "Reliable but slightly dinged"

when 6...10

puts "Can be a struggle"

when 10...30

puts "Clunker"

else

puts "Vintage gem"

end

succ


succ用来得到一个对象的下一跳

自定义序列

一个类必须实现succ方法,放回下一跳。

同时要实现空间船方法<=>

class PowerOfTwo

attr_reader :value

def initialize(value)

@value = value

end

def <=>(other)

@value <=> other.value

end

def succ

PowerOfTwo.new(@value + @value)

end

def to_s

@value.to_s

end

end

p1 = PowerOfTwo.new(4)

p2 = PowerOfTwo.new(32)

puts (p1..p2).to_a

IO


File


open

open方法和new方法都可以打开一个文件,但是open方法还可以和块一起工作。这样,仅仅需要把想要的操作放到块里面就可以,不需要处理文件的细节。比如异常。

迭代器

1.each_byte

File.open("testfile") do |file|

file.each_byte {|ch| print "#{ch.chr}:#{ch} " }

end

2.each_line

File.open("testfile") do |file|

file.each_line {|line| puts "Got #{line.dump}" }

end

IO


foreach

IO的foreach方法结合了打开和迭代,因此更加简单

IO.foreach("testfile") {|line| puts line }

StringIO

把String当做流

require 'stringio'

ip = StringIO.new("now is\nthe time\nto learn\nRuby!")

op = StringIO.new("", "w")

ip.each_line do |line|

op.puts line.reverse

end

op.string # => "\nsi won\n\nemit eht\n\nnrael ot\n!ybuR\n"

迭代器


外部迭代器


Ruby中传统的迭代器并不像其他语言中的迭代器那样会得到每一个元素,他仅仅是在对象中对每一个元素调用块。因此在ruby1.9中实现了一个Enumerators,相当于传统的迭代器

创建迭代器

enum_a = a.to_enum

enum_a = a.each

使用迭代器

enum_a.next

next

rewind

把迭代重新开始

注意

1.迭代器在迭代已经开始时,无法拷贝

zip

内部迭代器

each以及相似的接受一个快来迭代的方法,这儿迭代中的数据没有显式出现在客户代码中,仅仅出现在块中。