欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ruby code block  

程序员文章站 2022-07-14 12:32:56
...
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}