ITeye博客

ruby code block

mistbow · 2013-02-04 22:15 · Web前端 · Markdown

find

(1..5).find {|i| i == 5}
>5

(1..10).find {|i| i % 3 == 0}
>3

只返回第一个

(1..10).detect {|i| i % 3 == 0}
>3

(1..10).detect {|i| (1..10).include?(i * 3)}
>1

(1..10).find_all {|i| i % 3 == 0}
>[3, 6, 9]

(1..10).select {|i| (1..10).include?(i * 3)}
>[1, 2, 3]

(1..10).any? {|i| i % 3 == 0}
>true

(1..10).all? {|i| i % 3 == 0}
>false

[1..10].delete_if {|i| i % 3 == 0}
>[1, 2, 4 ,5, 7, 8, 10]


find/detect => Object or nil find_all/select => Array any? => Boolean all? => Boolean delete_if => Array

search

h1 = { "a" => 111, "b" => 222}
h2 = {"b" => 333, "c" => 444}

h1.merge(h2)
>{“a”=>111, "b"=>333, "c"=>444}
h1.merge(h2)
>{"a"=>111, "b"=>222, "c"=>444}

h1.merge(h2) {|key, old, new| new}
>{“a”=>111, "b"=>333, "c"=>444}

h1.merge(h2) {|key, old, new| old}
>{"a"=>111, "b"=>222, "c"=>444}

h1.merge(h2) {|key, old, new| old * 5}
>{"a"=>111, "b"=>1110, "c"=>444}

h1.merge(h2) do |key, old, new|
    if old < new
      old
    else
      new
    end
end

merge后面的会覆盖前面的

h1.merge(h2) {|k, o, n| o < n ? o : n}

{"a"=>111, "b"=>222, "c"=>444}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。