Use lambda in Ruby
九筒一条
http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
Understanding Ruby Blocks, Procs and Lambdas
Blocks, Procs and lambdas (referred to as closures
in Computer Science) are one of the most powerful aspects of Ruby, and
also one of the most misunderstood. This is probably because Ruby
handles closures in a rather unique way. Making things more complicated
is that Ruby has four different ways of using closures, each of which is
a tad bit different, and sometimes nonsensical. There are quite a few
sites with some very good information about how closures work within
Ruby. But I have yet to find a good, definitive guide out there.
Hopefully, this tutorial becomes just that.
First Up, Blocks
The most common, easiest and arguably most “Ruby like” way to use
closures in Ruby is with blocks. They have the following familiar
syntax:
array
=
[
1
,
2
,
3
,
4
]
array
.
collect!
do
|
n
|
n
**
2
end
puts
array
.
inspect
# => [1, 4, 9, 16]
So, what is going on here?
First, we send the collect!
method to an Array with a
block of code.
The code block interacts with a variable used within the collect!
method (n
in this case) and squares it.
Each element inside the array is now squared.
Using a block with the collect!
method is pretty easy,
we just have to think that collect!
will use the code
provided within the block on each element in the array. However, what
if we want to make our own collect!
method? What will it
look like? Well, lets build a method called iterate!
and
see.
class
Array
def
iterate!
self
.
each_with_index
do
|
n
,
i
|
self
[
i
]
=
yield
(
n
)
end
end
end
array
=
[
1
,
2
,
3
,
4
]
array
.
iterate!
do
|
n
|
n
**
2
end
puts
array
.
inspect
# => [1, 4, 9, 16]
To start off, we re-opened the Array class and put our iterate!
metho
相关文档:
我们知道ruby中对于整数的[],[]=,<<,>>操作是针对于二进制的值来运算的。
我现在写一个针对十进制数操作的类,拥有整数的所有方法,如下:
class InterEx
def initialize(val=0)
@val=val
end
def to_s
@val.to_s
end
def [](idx)
self.to_s[idx].to_i
end
d ......
使用 will_paginate 进行分页和简单查询
在命令行下使用 gem install will_paginate 命令,出现下面结果安装成功
打开 books_controller.rb (你自己的控制器)
注释掉查找全部的方法,使用下面的方法,已经集成根据title进行查询
Ruby代码
#@books = Book.all
@books = Book.pagina ......
前言
在《Routing的载入》中,我大致介绍了一下Rails中最简单的route是如何加载的。这篇文章,我将来讲一讲Rails系统中更为复杂的named route和与RESTful相关的resource是如何被加载的。为了不重复太多的笔墨,这篇文章将在前文的基础上进行,如果发现单独看此文时,有少许云里雾里,建议先看一看我的前篇文章:R ......
Ruby 类的继承
关键字: Ruby 类的继承
一、普通方式的继承
Ruby只支持单继承
ruby 代码
class
Child < Father
......
end
Object是所有类的始祖,并且Object的实例方法 ......
开发环境
Ruby:Ruby1.9.1
Rails:Rails2.3.5
Mysql:Mysql5.0.9
Driver:mysql-2.8.1-x86-mingw32.gem
IDE:Rubymine2.0.1
一、创建View/login
在View/login下创建login.html.erb、index.html.erb、loginFail.html.erb
login.html.erb代码如下:
<h1>Welcome to login!</h1>
<% form_tag do %>
& ......