Code
  • 首页
  • cpu-architecture
  • performance
  • c++
  • branch-prediction
  • java
2025-05-22 05:00:05

如何分割(块)一个Ruby数组成X元素的部分?

arraysruby

我有一个数组

foo = %w(1 2 3 4 5 6 7 8 9 10)

我如何将其分割或“块”成更小的数组?

class Array
  def chunk(size)
    # return array of arrays
  end
end

foo.chunk(3)
# => [[1,2,3],[4,5,6],[7,8,9],[10]]

看看Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
2010-04-23 15:04:50

如果你正在使用rails,你也可以使用in_groups_of:

foo.in_groups_of(3)
2011-11-22 00:16:43

推荐文章

  • 使用C返回一个数组
  • 是否可以在MiniTest中运行单个测试?
  • 如何在Ruby中生成a和b之间的随机数?
  • 向对象数组添加属性
  • 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
  • 如何在Ruby中创建文件
  • JavaScript在数组中
  • 什么是Ruby文件。开放模式和选项?
  • Ruby数组到字符串的转换
  • 如何分割(块)一个Ruby数组成X元素的部分?
  • Ruby中“or”和||的区别?
  • 使用lodash将对象转换为数组
  • 从数组中随机选择一个元素
  • 如何测试参数是否存在在轨道
  • 如何在Java中将int[]转换为Integer[] ?

aliyun

最新文章

  • 如何删除默认的导航栏空间在SwiftUI导航视图
  • 我可以列出所有的标准Go包吗?
  • 证书验证失败:无法获得本地颁发者证书
  • 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
  • 打开同一目录两次
  • 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
  • NullInjectorError: AngularFirestore没有提供程序
  • 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
  • 从元组/数组值派生联合类型
  • 如何在Angular2中截断文本?
  • 安装tzdata非交互式
  • ionic 2 - Error在Android Studio中找不到Gradle的安装版本
  • 如何查看所有地区所有正在运行的Amazon EC2实例?
  • 当使用pip3安装包时,“Python中的ssl模块不可用”
  • 安装APK时出现错误

标签

cpu-architectureperformancec++branch-predictionjavaundogit-commitgitversion-controlgit-remotegit-pushgit-branchgit-pullgit-fetchpythongeneratoriteratorjsonmime-typescontent-typearraysjavascriptgit-addcode-formattingcstandards-complianceoperatorscommentsdynamic-memory-allocationstackmemory-managementheap-memorylanguage-agnosticoverwritebackground-colorbrowserhtmldomjqueryvisibilityuse-strictsyntaxjslintremote-branchgit-checkoutpython-moduleidiomsprogram-entry-pointnamespacesbranch
2025 code 京ICP备15047053号-1