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,这里 ......
分页中用到类变量,主要是用来标记“页码输入框”的id 如果一个页面有几个分页,“页码输入框”的id要是不同的才能分清是哪个要分页。使用类变量就是为了达到这个目的,让所有的对象实例共用一个变量,不必每次重新初始化变量。 类变量使用代码示例 1 require 'ruby-debug'
2 debugger
3 cla ......
class Point
@x = 1
@y = 2
def initialize(x,y)
@x,@y = x,y
end
end
代码中的@x,@y为实例变量,实例变量只对self的环境起作用,因此initialize外面的@x=1,@y=2只对类本身起作用,而方法内部,的@x,@y是对对象的实例起作用的。
class Point
include Enumerable
def initialize(x ......
我们在使用C编程时会遇到一个问题,比如头文件的一个函数包含在一个lib中,但是
在实际连接中我们不知道它在哪个库中。也许可行的一种办法是直接上网查询某个
函数的依赖条件,这对于常用函数是没问题的!但是对于复杂而又缺少文档的第三方
lib来说,无异于大海捞针。
自此通过2种办法来尝试解决这个问题,我们先看第一 ......
Ruby 类的继承
关键字: Ruby 类的继承
一、普通方式的继承
Ruby只支持单继承
ruby 代码
class
Child < Father
......
end
Object是所有类的始祖,并且Object的实例方法 ......