美文网首页
4.容器、Block、迭代器

4.容器、Block、迭代器

作者: 风暴英雄 | 来源:发表于2014-04-14 16:23 被阅读0次
迭代常用方法

each
[1, 2, 3, 4, 5].each {|i| puts i}

find
[1,2,3,4,5,6].find {|i| i*i > 30} # 返回6

collectmap 方法一样,通过block返回一个新的数组
["H" , "A" , "L" ].collect {|x| x.succ } # => ["I", "B", "M"]
还有一个重要的方法是with_index
f = File.open("testfile")
f.each.with_index do |line, index|
puts "Line #{index} is: #{line}"
end
f.close

我们可以是在数组或hash中使用to_enum方法,转换成功枚举对象:
a = [ 1, 3, "cat" ]
h = { dog: "canine" , fox: "vulpine" }
# Create Enumerators
enum_a = a.to_enum
enum_h = h.to_enum
enum_a.next # => 1
enum_h.next # => [:dog, "canine"]
enum_a.next # => 3
enum_h.next # => [:fox, "vulpine"]

使用方法loop来控制枚举对象

short_enum = [1, 2, 3].to_enum
long_enum = ('a' ..'z' ).to_enum
loop do
puts "#{short_enum.next} - #{long_enum.next}"
end
produces:
1 - a
2 - b
3 - c

对数组或字符串的其他常用迭代方法:

result = []
[ 'a' , 'b' , 'c' ].each_with_index {|item, index| result << [item, index] }
result # => [["a", 0], ["b", 1], ["c", 2]]

result = []
"cat".each_char.each_with_index {|item, index| result << [item, index] }
result # => [["c", 0], ["a", 1], ["t", 2]]

result = []
"cat".each_char.with_index {|item, index| result << [item, index] }
result # => [["c", 0], ["a", 1], ["t", 2]]

enum = "cat".enum_for(:each_char)
enum.to_a # => ["c", "a", "t"]

enum_in_threes = (1..10).enum_for(:each_slice, 3)
enum_in_threes.to_a # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

相关文章

  • 4.容器、Block、迭代器

    迭代常用方法 each[1, 2, 3, 4, 5].each {|i| puts i} find[1,2,3,4...

  • Python 中的迭代器

    Python 中的迭代器 Python 3中的迭代器 容器与迭代器 在Python 3中,支持迭代器的容器,只要支...

  • 设计模式之迭代器模式

    迭代器模式 迭代器接口 具体迭代器类 容器接口 具体容器类 客户端 个人理解 在java中的集合是迭代器模式的最好...

  • NSMutableArray的遍历及删除

    for循环、快速循环forin、迭代器 NSEnumerator、迭代器的block形式 [array enume...

  • 容器类(list | vector | deque | set)

    常见容器类: 容器配接器: 迭代器 示例

  • 头文件中的迭代器

    头文件 中定义了四种迭代器: 插入迭代器(insert iterator):这些迭代器被绑定到一个容器上,可向容器...

  • 迭代器模式

    Iterator(迭代器接口):ConcreteIterator(迭代器实现类):Aggregate(容器接口):...

  • C++boolan part3_week4

    1. 迭代器 1.1 迭代器的种类 使用随机访问迭代器的容器:array, vector,deque使用双向迭代器...

  • STL容器

    STL容器迭代器 STL容器迭代器失效情况分析、总结[https://ivanzz1001.github.io/r...

  • python 迭代器 学习笔记

    迭代器:首先要明确的概念是迭代器不是容器,迭代器就是为了实现__next__()方法的对象(用于遍历容器中的数据)...

网友评论

      本文标题:4.容器、Block、迭代器

      本文链接:https://www.haomeiwen.com/subject/kpeltttx.html