How do I use “slice_before” with initial_state in Ruby 1.9?
来源:互联网 发布:如何注销淘宝会员名 编辑:程序博客网 时间:2024/05/18 03:05
saw Ruby 1.9 has a new enumerator, slice_before
. The API docs are pretty cryptic.
In particular I'm baffled by the variation that takes an initial_state
value.
For example, I want to split an array with numbers into sub-arrays whenever the progressive sum of the elements exceeds some value:
a = [1,2,0,1,2,3]a.slice_before(0) do |elem, sum| sum += elem sum > 3end.to_a
Expected output:
[[1,2,0], [1,2], [3]]
I'm thinking the sum is like a "carry" or "memo" as in inject
but that doesn't seem to pan out.
The glitch in this code is a cryptic error:
TypeError: can't dup Fixnumfrom (irb):43:in `each'
It looks like slice_before
doesn't accept a Fixnum
as initial value. Why? Ruby bug?.
I can work around this by keeping my own state variable, but it's not quite the beautiful Ruby semantic I was looking for.
sum = 0a.slice_before do |elem| sum += elem sum > 3 && sum = 0end.to_a# => [[1, 2, 0], [1, 2], [3]]
So is initial_state
usable for this purpose, or not? The examples in the docs seem to be mostly about text processing. I'm using Ruby 1.9.3p194.
The initial_state
is typically a state hash that stores key-value pairs.
To write your code using a state hash:
a.slice_before(sum: 0) do |elem, state| state[:sum] += elem state[:sum] > 3 && state[:sum] = 0end.to_a
The initial_state
must respond to the #dup
method, because it is duplicated on each loop.
The reason Fixnum
doesn't work is because it doesn't respond to #dup
. A Fixnum wouldn't work because it can't keep track of state on each loop.
- How do I use “slice_before” with initial_state in Ruby 1.9?
- How do I use Cygwin in Geophysics ?
- How do I use WPF bindings with RelativeSource?
- How do I use Form authentication with Tomcat?
- How do I use Spring Property Placeholder with Camel XML
- How do I install and use fonts in Linux?
- How do I use IStream?
- UE4 How do I use InstancedStaticMeshes ?
- ActiveMQ - How do I use SSL
- [转]How do I use cygwin1.dll with Visual Studio or MinGW?
- How do I use the DCMTK libraries in my own application?
- How Do use the ImageButton in DataGrid...
- How do I read in a character variable with varying length in a space delimited dataset?
- How do I read in a character variable with varying length in a space delimited dataset?
- How Do I get Started with Oracle?
- How do I get started with CUDA?
- How do I install a file in my local repository along with a generic POM?
- How do I debug JavaScript in Safari?
- bootsrap使用过程中的报错和对产品的看法
- 双向链表分析
- C++模板
- up
- socket中TCP建立连接与释放连接
- How do I use “slice_before” with initial_state in Ruby 1.9?
- 条款10:令operator = 返回一个reference to *this
- 阿里巴巴2014产品经理实习生提案三
- 用户与Oracle数据库服务器建立连接
- LeetCode: Minimum Path Sum [063]
- cocos2d-x 3.0 关于新建listview后出现白屏的情况
- 面向对象设计原则概述
- 90后IT毕业生调查:不想做IT民工,想做马云
- Learn Python The Hard Way exercise 42