红宝石集合/枚举的酷技巧和富有表现力的片段[关闭]

2023-12-27

您最喜欢的 Ruby 集合代码片段是什么?最好它们应该是你的发现,具有表现力,可读性,并为你的编码实践带来一些乐趣。


数组中的模式匹配(对于局部变量和参数):

(a, b), c = [[:a, :b], :c]
[a,b,c]
=> [:a, :b, :c]

(a,), = [[:a]]
a
=> :a

从非数组分配给多个变量:

abc, a, b =* "abc".match(/(a)(b)./)
=> ["abc", "a", "b"]

nil1, =* "abc".match(/xyz/)
=> []

使用相同的表达式初始化数组元素:

5.times.map { 1 }    
=> [1,1,1,1]

Array.new(5) { 1 }
=> [1,1,1,1,1]

使用相同的值初始化数组:

[2]*5
=>[2,2,2,2,2]

Array.new 5, 2
=>[2,2,2,2,2]

数组元素的总和:

[1,2,3].reduce(0, &:+)

=> 6

查找所有符合条件的索引:

a.each_with_index.find_all { |e, i| some_predicate(e) }.map(&:last)

备用 CSS 类:

(1..4).zip(%w[cls1 cls2].cycle)

=> [[1, "cls1"], [2, "cls2"], [3, "cls1"], [4, "cls2"]]

解压:

keys, values = {a: 1, b: 2}.to_a.transpose
keys
=> [:a, :b]

探索字符串的布尔成员方法:

"".methods.sort.grep(/\?/)

探索特定于字符串的方法:

"".methods.sort - [].methods

带记忆的惰性斐波那契数列,取自尼拉吉·辛格 http://Neeraj.Name/2008/05/10/how-hash-works-with-block-in-ruby.html:

fibs = { 0 => 0, 1 => 1 }.tap do |fibs|
  fibs.default_proc = ->(fibs, n) { fibs[n] = fibs[n-1] + fibs[n-2] }
end

fibs.take(10).map(&:last).each(&method(:puts))

计数排序的实现:

module Enumerable
  def counting_sort(k)
    reduce(Array.new(k+1, 0)) {|counting, n| counting.tap { counting[n] += 1 }}.
    map.with_index {|count, n| [n] * count }.flatten
  end
end

一个实现sum又名前缀和:

module Enumerable
  def scan(initial=nil, sym=nil, &block)
    args = if initial then [initial] else [] end
    unless block_given?
      args, sym, initial = [], initial, first unless sym
      block = ->(acc, el) { acc.send(sym, el) }
    end
    [initial || first].tap {|res| 
      reduce(*args) {|acc, el| 
        block.(acc, el).tap {|e|
          res << e
        }
      }
    }
  end
end

在这里,我尝试了Hash#each yield KeyValuePairs 而不是二元Arrays。相当令人惊讶,代码量有多少still在做了如此残酷的猴子补丁之后,工作正常了。耶,鸭子打字!

class Hash
  KeyValuePair = Struct.new(:key, :value) do
    def to_ary
      return key, value
    end
  end

  old_each = instance_method(:each)
  define_method(:each) do |&blk|
    old_each.bind(self).() do |k, v|
      blk.(KeyValuePair.new(k, v))
    end
  end
end

我一直在玩的东西是Enumerable#===执行递归结构模式匹配。我不知道这是否有任何用处。我什至不知道它是否真的有效。

module Enumerable
  def ===(other)
    all? {|el| 
      next true if el.nil?
      begin
        other.any? {|other_el| el === other_el }
      rescue NoMethodError => e
        raise unless e.message =~ /any\?/
        el === other
      end
    }
  end
end

我最近玩弄的另一件事是重新实现所有方法Enumerable,但是使用reduce代替each作为基础。在这种情况下,我know它实际上不能正常工作。

module Enumerable
  def all?
    return reduce(true) {|res, el| break false unless res; res && el } unless block_given?
    reduce(true) {|res, el| break false unless res; res && yield(el) }
  end

  def any?
    return reduce(false) {|res, el| break true if res || el } unless block_given?
    reduce(false) {|res, el| break true if res || yield(el) }
  end

  def collect
    reduce([]) {|res, el| res << yield(el) }
  end
  alias_method :map, :collect

  def count(item=undefined = Object.new)
    return reduce(0) {|res, el| res + 1 if el == item } unless undefined.equal?(item)
    unless block_given?
      return size if respond_to? :size
      return reduce(0) {|res, el| res + 1 }
    end
    reduce(0) {|res, el| res + 1 if yield el }
  end

  def detect(ifnone=nil)
    reduce(ifnone) {|res, el| if yield el then el end unless res }
  end
  alias_method :find, :detect

  def drop(n=1)
    reduce([]) {|res, el| res.tap { res << el unless n -= 1 >= 0 }}
  end

  def drop_while
    reduce([]) {|res, el| res.tap { res << el unless yield el }}
  end

  def each
    tap { reduce(nil) {|_, el| yield el }}
  end

  def each_with_index
    tap { reduce(-1) {|i, el| (i+1).tap {|i| yield el, i }}}
  end

  def find_all
    reduce([]) {|res, el| res.tap {|res| res << el if yield el }}
  end
  alias_method :select, :find_all

  def find_index(item=undefined = Object.new)
    return reduce(-1) {|res, el| break res + 1 if el == item } unless undefined.equals?(item)
    reduce(-1) {|res, el| break res + 1 if yield el }
  end

  def grep(pattern)
    return reduce([]) {|res, el| res.tap {|res| res << el if pattern === el }} unless block_given?
    reduce([]) {|res, el| res.tap {|res| res << yield(el) if pattern === el }}
  end

  def group_by
    reduce(Hash.new {|hsh, key| hsh[key] = [] }) {|res, el| res.tap { res[yield el] = el }}
  end

  def include?(obj)
    reduce(false) {|res, el| break true if res || el == obj }
  end

  def reject
    reduce([]) {|res, el| res.tap {|res| res << el unless yield el }}
  end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

红宝石集合/枚举的酷技巧和富有表现力的片段[关闭] 的相关文章

随机推荐

  • 环境变量和@Value不能在Spring Boot上一起工作

    我有一个 Spring boot 应用程序 它连接到用作缓存的 Redis 实例 当我在开发环境中时 我有以下内容 spring profiles default redis host localhost port 6379 而我的缓存配置
  • 如何使用Firebug或其他查看WS/WSS Websocket请求内容?

    有没有办法查看Websocket流量 首次握手时仅可见 Websocket 标头 响应后一切都消失了 Connection Upgrade Sec WebSocket Accept EQqklpK6bzlgAAOL2EFX nx8bEI U
  • 在asp.net中动态添加

    标签用于评论系统

    我正在为我的网页制作一个评论框 我设计了一个表单来获取用户名和评论并将其存储在数据库表中 我不知道如何在页面上呈现该数据 通过迭代表格并随后在页面上创建段落或在页面上创建标签 我在 C 中使用 LINQ to SQL 请告诉我如何在网页或教
  • 带子图的猫图有限制吗? [复制]

    这个问题在这里已经有答案了 Seaborn 的 catplot 似乎无法与 plt subplots 一起使用 我不确定这里有什么问题 但我似乎无法将它们并排放置 Graph 1 plt subplot 121 sns catplot x
  • 清理数组

    我有一个动态生成的表单 最终用户将能够向数据库提交员工详细信息 因此数组 fname 将包含所有名字 lname 将包含所有姓氏等 然后将数组插入到 MySQL 中 如下所示 query INSERT INTO workers date a
  • 打印空行有什么作用?

    我知道这个问题很可能是您今天听到的最愚蠢的问题 但对我来说 这是我编程学习现阶段的一个大问题 为什么这段 Python 代码中需要第二个空行 那条线有什么作用 print Content Type text plain print prin
  • 我可以在 tmux 中双击选择并复制吗?

    我正在学习使用 tmux 我发现当我在 tmux 窗口中时 双击选择和复制功能不再起作用 我可以像 iterm2 一样使用双击来选择和复制吗 我用谷歌搜索了一段时间 但没有找到简短而明确的答案 我已经添加了setw g mode mouse
  • 按地址获取符号(符号二进制,iOS 构建)

    我有分配工具的快照 其中包含有趣符号的地址 我想知道这个地址在代码中的位置 我有相应的 dSYM 文件 我尝试使用atosym命令行工具 但它给了我错误的符号 与我的应用程序无关 如何获得 PS 二进制文件由XCode 4 3 2构建 代码
  • ./deploy.sh 不适用于 gitlab ci

    我的问题是我创建的 bash 脚本出现此错误 bin sh eval 第 88 行 deploy sh 未找到 在 gitlab 上 下面是我的示例脚本 gitlab ci yml 我怀疑 gitlab ci 不支持 bash 脚本 ima
  • Python 中的正则表达式用于检测整数、浮点数或科学记数法中的数字

    如何在 Python 中创建接受数字的正则表达式 这些数字可以是整数 浮点数 也可以是 3e 3 或 3e 3 格式 我只想匹配字符串的开头 如果存在上述任何格式的数字 则返回该数字和字符串的其余部分 Edit 例如 输入 gt gt 29
  • PHP、Javascript 和 SQL 代码混淆

    您好 我有这段代码可以从数据库中提取客户名称和地址 它回显下拉列表中每个条目的客户端名称
  • 无法通过 Android 应用程序正确加载 Facebook 页面

    我想通过我的 Android 应用程序单击按钮打开我的 Facebook 页面 我目前正在使用以下代码 如此处所回答 从 Android 应用程序打开 Facebook 页面 https stackoverflow com question
  • 实体框架 6.1 中的模拟 DbContext

    我发现了许多示例 显然 显示了使用 EF 6 模拟 DbContext 的清晰工作示例 但是 它们似乎都不适合我 我也不完全确定原因 这是我设置模拟的单元测试代码 var mockData new List
  • 学习 Smalltalk 最好的免费 IDE 是什么? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 您认为学习 SmallTalk 的好 IDE 是什么 我只是将它用作业余爱好 所以它必须是免费的 你还应该考虑Pharo http pha
  • Airflow Scheduler 无法通过 WSL 执行 Windows EXE

    我的 Windows 10 计算机在 WSL 2 Ubuntu 20 04 中安装了 Airflow 1 10 11 我有一个 BashOperator 任务 它在 Windows 上调用 EXE 通过 mnt c 或通过符号链接 任务失败
  • 在swift中使用bridgeToObjectiveC()

    什么是桥接目标C 会很快做的 看起来就像转换一个Swift对象进入ObjectiveC目的 这与类型转换相同吗 例如我可以转换 swiftString into NSString like var swingString String te
  • Docker swarm 未公开端口

    我正在尝试在单个节点上运行 docker swarm 但无法将 docker 应用程序端口暴露给主机 这很相似Docker swarm 服务端口未暴露 https stackoverflow com questions 54121566 d
  • 将 FontWeight 设置为 Bold 可缩小文本大小

    我一直在设置资源字典来设置 WPF 应用程序中所有控件的样式 并且在设置标签的字体粗细时发现了一些奇怪的行为 我必须为标签设置样式 第一个具有正常的字体粗细 第二个设置为粗体
  • 在 Visual Studio 2012 中创建控制器时出错

    我正在尝试学习 ASP NET MVC 因此我正在关注 asp net 网站上的音乐商店教程 我正在使用 Album cs 作为模型类和 MusicStoreEntities cs 作为数据上下文类来创建 StoreManagerContr
  • 红宝石集合/枚举的酷技巧和富有表现力的片段[关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi