posts - 403, comments - 310, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Ruby 入门笔记 (1)

Posted on 2007-06-14 14:02 ZelluX 阅读(328) 评论(0)  编辑  收藏 所属分类: Scripting
先把各种热门的东西都走马观花地看一遍,呵呵。
看的是Everyday Scripting with Ruby,风格和In Action系列差不多,大量的实例。
现在学Ruby的主要目的也是everyday scripting,方便数据处理、生成,文件批处理等,RoR之类的暂时不考虑。

1. String.inspect 方法
文档中的说法是
     str.inspect   => string

     Returns a printable version of _str_, with special characters
     escaped.

        str = "hello"
        str[3] = 8
        str.inspect       #=> "hel\010o"

具体情况试试 myString.inspect.inspect....就能了解一点了

2. Arrays.each 和 Arrays.collect
for_each方法

irb(main):007:0> [1, 2, 3].each do | element |
irb(main):008:1*   puts element
irb(main):009:1> end
1
2
3
=> [1, 2, 3]

后者与前者的不同之处在于,在处理数据的同时,每次处理的返回结果都会保存到一个新的数组中返回。
irb(main):036:0> newarray = ["aBC", "B"].collect do |e|
irb(main):037:1* e.downcase
irb(main):038:1> end
=> ["abc", "b"]

3. Messages and Methods
It can be hard to remember the difference between messages and methods. A message is a request sent from some sender object. When the receiver object receives the message, it looks to see whether it has a method with the same name. If so, the Ruby code within the method is run, and the results are returned to the sender. The message is the request; the method fulfills it.
呃,还是没有感性认识。

4. Delimiting Blocks
块的两种表示方式:
array.each do | element |
    puts element
end
array.each { | element |
    puts element
}
通常使用第一种,但可以用一行写成的情况也可以使用第二种:
array.each { | element | puts element }



只有注册用户登录后才能发表评论。


网站导航: