---
title: "ruby 杂记"
author: "yangbinfc"
date: "2011-06-03T09:11:00Z"
tags: []
slug: "ruby"
draft: false
lastmod: "2012-11-04T17:47:25Z"
id: 1715325
url: "https://yangbinfc.iteye.com/blog/1715325"
---

1：arr.\_\_send\_\_strategy send动态调用方法 那个strategy方法

2：Java 不能直接传递方法，所以把简单的问题复杂化了…… ruby可以把方法块传递过去，这就是他强大的一面

3：Duck Typing (check respond\_to? instead of class) 早已解耦，根本不需要中介。

4：ruby中控制循环的是： break next ；next相当于java中的continue 是继续下层循环

5：ruby中的正则表达式：

/^http:////(**\[^//]** +)/ :【^//】的意思是值包含除了 ^后面的字符外的字符

( /^http:////(**\[^//]** +)/ ).march(str)**\[1]** 匹配的是http://linux.org 中的linux.org

6:ruby正则表达式学习网站：

http://www.rubular.com/r/OC692OE7wg

7:ruby这个符号||=

作用：有值就不赋值 无值就赋值 ep:a ||=3 a = a || 3

8:动态生成实例方法：

ruby：class\_eval{}

9:

```
respond_to :html
, :xml
, :json
```

现在，我的这个controller中所有的action都支持这3种格式了，是不是比在rails2中的每个action中都写 format.html, format.xml等方便多了。观众举手发问：“如果我只想在index中接受html格式，但在show中接受json格式怎么办？”，哈 哈，Rails3也为我们想到了这个问题，**respond\_to 方法可以和before\_filter方法一样接受only和except方法，与此同时respond\_with也接受block的书写方式，这样你就可以随心所欲的定制格式了。**

好，继续往下。如果你足够细心，你就会发现以前十几行代码量的create变的只有5行了。如下

```
1

2

3

4

5

```

```
  def
 create


    @post
 = Post.new(params[:post
])

    flash[:notice
] = 'Post
 was successfully created.
'

 if
 @post
.save

    respond_with(@post
)

  end
```