注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

星期五

明天不上班

 
 
 

日志

 
 
关于我

一个特立独行的Java程序员,比较宅,上上网,写博客,听音乐,看电影。

网易考拉推荐

Ruby基本知识(四)  

2012-01-15 11:34:47|  分类: Ruby |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
#容器(Array and Hash)
#创建数组 与 Java中的数组不同 Java数组必须是同一类型
a = [1, "string", true]
puts a.to_s
#数组访问
puts a[0]
puts a[2]
#当数组中的元素不存在的时候,返回nil
puts a[5].to_s

#对数组重新赋值
a[0] = 10
a[5] = 15
puts a[0]
puts a[5]

#另一种创建数组方式
b = Array.new
puts b.to_s -> []
puts b.length
c = Array.new(3)
puts c.to_s  -> [nil, nil, nil]
puts c.length

#其他访问方式 a[start, count]
a = [1, "string", true, false, "IBM", "Platform"]
puts a[1, 3].to_s -> ["string", true, false]

#多维数组

#定义一个散列Hash

h = { "a"=>"b", 1=>true, "string"=>true}
puts h.to_s
#访问Hash的值
puts h["string"]
puts h["string"].class

#关于Array的一些常用方法
http://www.ruby-doc.org/core-1.9.2/Array.html#method-c-5B-5D

下面是url中一些内容的摘抄

# & 用于取两数组的交集 ary & other_ary -> new_ary
[1, 2]&[1,3,5] #=> [1]

# ary * int -> new_ary
[1, 2]*3 #=> [1, 2, 1, 2, 1, 2]

# ary * str -> new_string
[1,2]*"s" #=> "1s2"

#ary + other_ary -> new_ary
[1, 2, 3] + [4, 5] #=> [1, 2, 3, 4, 5]

#ary << obj -> ary
[1, 2] << 3 << "c" << [5, 6] << true #=> [1, 2, 3, "c", [5, 6], true]

#ary <=> other_ary -> -1, 0, 1 or nil
[1,2,3] <=> [1,2] #=> 1

#ary == other_ary -> bool
[1,2,3] == [1,2] #=> false

#访问数组元素
#ary[index] -> object or nil
#ary[start, length] -> new_ary or nil
#ary[range] -> new_ary or nil
a = [1, 2, 3, 4]
a[1..2] #=> [2,3]
a[1...2] #=> [2]
a[1...10] #=> [2, 3, 4]

#数组元素赋值
#ary[index] = obj → obj
#ary[start, length] = obj or other_ary or nil → obj or other_ary or nil
#ary[range] = obj or other_ary or nil → obj or other_ary or nil
a[1...10] = 10 #=> [1, 10]

#查找数组元素
#assoc(obj) → new_ary or nil

s1 = [ "colors", "red", "blue", "green" ]
s2 = [ "letters", "a", "b", "c" ]
s3 = "foo"
a  = [ s1, s2, s3 ]
a.assoc("letters")  #=> [ "letters", "a", "b", "c" ]
a.assoc("foo")      #=> nil

#clear → ary 清空数组
a.clear #=> []

#下面的两个方法没有侵入性,不会改变数组本身
#collect {|item| block } → new_ary click to toggle source
#map {|item| block } → new_ary

a=[1, 2, 3]
a.collect{|x| x*2} #=> [2, 4, 6]
a #=> [1, 2, 3]

a.map{|x| x*2} #=> [2, 4, 6]

#下面的方法,具有侵入性,会改变数组本身
#collect! {|item| block } → ary click to toggle source
#map! {|item| block } → ary

#combination(n) { |c| block } → ary
a = [1, 2, 3, 4]
a.combination(1).to_a  #=> [[1],[2],[3],[4]]
a.combination(2).to_a  #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
a.combination(4).to_a  #=> [[1,2,3,4]]
a.combination(0).to_a  #=> [[]] # one combination of length 0
a.combination(5).to_a  #=> []   # no combinations of length 5

#compact → new_ary click to toggle source
#Returns a copy of self with all nil elements removed.
[1, 2, nil, 4].compact #=> [1, 2, 4]

#compact! → ary or nil
#Removes nil elements from the array. Returns nil if no changes were made, otherwise returns ary.
["a", nil, "b", nil].compact! #=> ["a", "b"]
["a", "b"].compact!           #=> nil

#count -> int 计算元素个数
#count(obj) -> int 计算obj在数组中的个数
#count{|item| block} ->int 根据block中的条件计算个数
ary = [1, 2, 4, 2] ary.count             #=> 4 ary.count(2)          #=> 2
ary.count{|x|x%2==0} #=> 3

#cycle(n=nil) {|obj| block } → n代表循环次数 nil代表无限次
a = ["a", "b", "c"] #a.cycle {|x| puts x } # a, b, c, a, b, c,.. forever. a.cycle(2) {|x| puts x } # a, b, c, a, b, c.
#delete(obj) -> obj or nil
#delete(obj){block} -> obj or nil

a = ["a", "b", "c", "d", "d", "d"]
a.delete("d")    #=> "d"
a               #=>["a", "b", "c"]
a.delete("e")   #=> nil

a = ["a", "b", "c", "d", "d", "d"]
a.delete("a"){ "a is found" } #=> a is found

#delete_at(index) => obj or nil
a = %w(a b c d e f g)
a.delete_at(2)  #=> "c"
a                 #=> ["a", "b", "d", "e", "f", "g"]
a.delete_at(10) #=> nil

#delete_if{|item| block} -> ary
a = %w(a b c d e f g)
a.delete_if{|i| i <= "f" } #=> ["g"]

#drop(n) -> new_ary
#Drops first n elements from ary, and returns rest elements in an array.
a = [1, 2, 3, 4, 5]
a.drop(2) #=> [3, 4, 5]

#drop_while{|arr| block} -> new_ary
a = [1, 2, 3, 4]
a.drop_while{|i| i < 2} #=> [2, 3, 4]

#each{|item| block} -> ary
a = %w(a b c d e f)
a.each{|x| print x*2}

#each_index{|index| block} -> ary
a.each{|i| print i + " " + a[i]}

#empty? -> true or false 判断数组是否有元素
a = Array.new(4) #=> [nil, nil, nil, nil]
a.empty? #=> false
a = Array.new #=> []
a.empty? #=> true

#fetch(index) -> obj if index is outside the array , throw IndexError
#fetch(index, default) -> obj if index is outside the array, return default
#fetch(index){|index| block} -> obj if index is outside the array, return block

a = [ 110, 22, 330, 44 ]
a.fetch(1)               #=> 22
a.fetch(-1)              #=> 44
a.fetch(4, 'default')        #=> "default"
a.fetch(5) { |i| i*i }   #=> 25

#fill(obj) → ary click to toggle source
#fill(obj, start [, length]) → ary
#fill(obj, range ) → ary
#fill {|index| block } → ary
#fill(start [, length] ) {|index| block } → ary
#fill(range) {|index| block } → ary

a = [ "a", "b", "c" ]
a.fill("x")              #=> ["x", "x", "x"]
a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"] 注意元素由3个变为4个
a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
a.fill {|i| i*i}         #=> [0, 1, 4, 9]
a.fill(-2) {|i| i*i*i}   #=> [0, 1, 8, 27]

#index(obj) → int or nil 根据对象返回索引
#index {|item| block} → int or nil 根据block返回索引

a = %w(0 1 2 3 4)
a.index("1") #=> 1
a.index{|x| x == "0"} #=> 0

a.index{|x| x >= "2"} #=> 2 返回第一个满足条件的元素索引

#first -> obj or nil 返回数组第一个元素
#first(n) -> new_ary 返回数组前n个元素

a = [0, 1, 2, 3, 4]
a.first        #=>0   
a.first(3) #=>[0, 1, 2]

#flatten → new_ary  对多维数组进行处理 将数组拉平
#flatten(level) → new_ary 

a = [ 1, 2, [3, [4, 5] ] ]
a.flatten   #=> [1, 2, 3, 4, 5]
a.flatten   #=> nil
a           #=> [ 1, 2, [3, [4, 5] ] ]
a.flatten(1) #=> [1, 2, 3, [4, 5]]

#flatten! → ary or nil
#flatten!(level) → array or nil

#frozen? → true or false
#include?(obj) → true or false

#replace(other_ary) → ary
a = [ "a", "b", "c", "d", "e" ]
a.replace([ "x", "y", "z" ])   #=> ["x", "y", "z"]
a                              #=> ["x", "y", "z"]

#insert(index, obj...) → ary
a = %w{ a b c d }
a.insert(2, 99)         #=> ["a", "b", 99, "c", "d"]
a.insert(-2, 1, 2, 3)   #=> ["a", "b", 99, "c", 1, 2, 3, "d"]

#join(sep=$,) → str 很喜欢的方法 类似于Java中StringUtils.join
["a", "b", "c", "d"].join        #=> "abcd"
["a", "b", "c", "d"].join("--")   #=> "a--b--c--d"

#last → obj or nil  类似于 first
#last(n) → new_ary

#pop -> obj or nil remove last ele
#pop(n) -> new_ary
a = %w(a b c d)
a.pop #=> "d"
a.pop(2) #=> ["b", "c"]

#product(other_ary, ...) → new_ary

#push(obj, ...) -> ary
a = %w(a b c d)
a.push(1, true) #=> ["a", "b", "c", "d", 1, true]

#rassoc(obj) → new_ary or nil 搜索数组
a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
a.rassoc("two")    #=> [2, "two"]
a.rassoc("four")   #=> nil

#reverse → new_ary
#reverse! → new_ary
#reverse_each {|item| block } → ary

#rindex(obj) → int or nil 于index方式一样,只不过是返回最后一个匹配成功的元素的索引
#rindex {|item| block} → int or nil

#rotate([n = 1]) → new_ary 把数组看成一个环,使其旋转n步
a = [ "a", "b", "c", "d" ]
a.rotate         #=> ["b", "c", "d", "a"]
a                #=> ["a", "b", "c", "d"]
a.rotate(2)      #=> ["c", "d", "a", "b"]

#rotate!(cnt=1) → ary

#select {|item| block } → new_ary 选择符合条件的数组元素
a = ["Java", "JavaScript", "Ruby", "Groovy"]
a.select {|item| item.start_with?("J")} #=> ["Java", "JavaScript"]

#select! {|item| block } → new_ary or nil

#shift → obj or nil
#Returns the first element of self and removes it
#shift(n) → new_ary

#sort → new_ary
#sort {| a,b | block } → new_ary



#关于Hash的一些常用方法
http://www.ruby-doc.org/core-1.9.3/Hash.html

关于Blocks
Blocks实现迭代器
举例
def three_times
    yield
    yield
    yield
end

three_times { puts "Hello"}
带参数
def three_times(name)
    yield name
    yield name
    yield name
end

three_times("Ruby") {|name| puts "Hello #{name}"}

数组中的一些迭代器
[1, 2, 4].find {|i| i > 1} #=> 2
[1, 2, 4].each {|i| puts i*i}
[1, 2, 4].collect {|i| i*i} #=> [1, 4, 16]
[1, 2, 4].inject {|sum, ele| sim + ele} #=> 7
[1, 2, 4].inject(3) {|sum, ele| sim + ele} #=> 10

Blocks实现闭包
书中的例子

class Button
    def initialize(label, &action) #&action 代表传一个Block
        @label = label
        @action = action
    end
   
    def button_pressed
        @action.call(self) #执行Block
    end
   
    attr_accessor :label
end

startButton = Button.new("start") {|button| puts "#{button.label}_button pressed"}
stopButton = Button.new("stop") {|button| puts "#{button.label}_button pressed"}
startButton.button_pressed
stopButton.button_pressed
  评论这张
 
阅读(279)| 评论(0)
推荐

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017