Ale*_*xey 5 ruby collections enumerable code-snippets
你最喜欢的带有 ruby 集合的代码片段是什么?最好它们应该是为您发现的、富有表现力的、可读的,并在您的编码实践中引入一些乐趣。
数组中的模式匹配(对于局部变量和参数):
(a, b), c = [[:a, :b], :c]
[a,b,c]
=> [:a, :b, :c]
(a,), = [[:a]]
a
=> :a
Run Code Online (Sandbox Code Playgroud)
从非数组分配给多个变量:
abc, a, b =* "abc".match(/(a)(b)./)
=> ["abc", "a", "b"]
nil1, =* "abc".match(/xyz/)
=> []
Run Code Online (Sandbox Code Playgroud)
使用相同的表达式初始化数组元素:
5.times.map { 1 }
=> [1,1,1,1]
Array.new(5) { 1 }
=> [1,1,1,1,1]
Run Code Online (Sandbox Code Playgroud)
用相同的值初始化数组:
[2]*5
=>[2,2,2,2,2]
Array.new 5, 2
=>[2,2,2,2,2]
Run Code Online (Sandbox Code Playgroud)
对数组元素求和:
[1,2,3].reduce(0, &:+)
=> 6
Run Code Online (Sandbox Code Playgroud)
查找所有符合条件的索引:
a.each_with_index.find_all { |e, i| some_predicate(e) }.map(&:last)
Run Code Online (Sandbox Code Playgroud)
替代 CSS 类:
(1..4).zip(%w[cls1 cls2].cycle)
=> [[1, "cls1"], [2, "cls2"], [3, "cls1"], [4, "cls2"]]
Run Code Online (Sandbox Code Playgroud)
解压:
keys, values = {a: 1, b: 2}.to_a.transpose
keys
=> [:a, :b]
Run Code Online (Sandbox Code Playgroud)
探索字符串的布尔成员方法:
"".methods.sort.grep(/\?/)
Run Code Online (Sandbox Code Playgroud)
探索特定于字符串的方法:
"".methods.sort - [].methods
Run Code Online (Sandbox Code Playgroud)
我自己的是:
使用相同的表达式初始化数组元素:
5.times.map { some_expression }
Run Code Online (Sandbox Code Playgroud)
使用相同的值初始化数组:
[value]*5
Run Code Online (Sandbox Code Playgroud)
数组元素的总和:
[1,2,3].reduce(0, &:+)
Run Code Online (Sandbox Code Playgroud)
查找所有符合条件的索引:
a.each_with_index.find_all { |e, i| some_predicate(e) }.map(&:last)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1764 次 |
| 最近记录: |