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
相关文档:
转自 http://www.advidea.cn/biancheng/200943135232.html
Ruby watir 测试框架
大多数人都会安装 ruby,
也通过Ruby 安装 gem,
也安装了ruby IDE开发工具:netbeans,
但就是不能跑watir环境,狂晕加吐中。。。
错误如下:
in `require': no such file to load -- watir (LoadError)
反正就是找不到watir,这里 ......
安装环境:
OS:Windows XP
Ruby: Ruby1.9.1
Mysql: Mysql5.1.46 (username/password: root/root port:3306)
Ruby-Mysql Driver: mysql-2.8.1-x86-mswin32.gem
(注:用2.7.3版本的驱动在测试时会出现 require"mysql",找不到指定模块 错误)
IDE:RubyMine2.0.1
安装Ruby,RubyMine,Mysql的事项在这里就不多 ......
ruby常规访问access数据库的方法应该是使用DBI库
:
require 'dbi'
DBI.connect("DBI:ADO:Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb;")
可是
简单尝试之后没能成功,提示找不到驱动器ADO,懒得再试,遂找其他方法。
一番搜索之后,发现可以用WIN32OLE来访问access,写一个简单的类包装之:
......