---
title: "eloquent ruby 读书笔记"
author: "夜鸣猪"
date: "2012-02-22T07:24:51Z"
tags: ["Ruby"]
categories: ["编程语言"]
slug: "eloquent-ruby"
draft: false
lastmod: "2012-02-23T03:23:51Z"
id: 1416313
url: "https://hlee.iteye.com/blog/1416313"
---

节省时间就草记，只记录新鲜，容易忘的

1.  case 的判断是three equal sign, 所以when中可以放正则表达式
2. set 和 sortset hybrid array hash 三种collection
3. false nil是false所以下面的写法是危险的

```ruby

if flag == true
  # do something
end
#advantage of the expression-oriented nature of Ruby 

```

4. 


```ruby
@first_name ||= ''
@first_name = '' unless @first_name
@first_name = @first_name || ''


```

使用例外，不要用来初始化，boolean。 因为，值是false，会执行初始化。

5. 

```ruby

load_font :name => 'times roman', :size => 12
#来自于
load_font( { :name => 'times roman', :size => 12 })

```


6. 
```ruby

%w{abcd des dfsw abc}.inject(0) { |sum, x| x.length + sum}
# => 14
%w{abcd des dfsw abc}.inject() { |sum, x| sum + x}
# => "abcddesdfswabc"  

```


7. 不带！号，还改变array的方法们
push, pop, delete, shift

8. 按照index循环，又删除元素，就会少循环到几个元素。


```ruby

array = [ 0, -10, -9, 5, 9 ]
array.each_index {|i| array.delete_at(i) if array[i] < 0}
p array
#=>[0, -9, 5, 9]


```


9. 什么时候用set，比如unique的array

```ruby

require 'set'
# => true 
word_set = Set.new %w(ac bd dd et ac)
# => #<Set: {"ac", "bd", "dd", "et"}> 


```


10.
Ruby strings are mutable