ruby - 如何在 Ruby 中为 String 类创建新函数?

标签 ruby

我想检查我遇到的字符串类型:

class String
    def is_i?
        /\A[-+]?\d+\z/ === self
    end

    def is_path?
        pn = Pathname.new(self)
        pn.directory?
    end     
end

def check(key)
    puts case key
    when is_i?
        puts "Could be a number"
    when is_path?
        puts "This is a path"
    else
        puts "Ok"
    end
end

当我运行 check("1345425") 时,出现以下错误:

undefined method `is_i?' for main:Object (NoMethodError)

我应该做什么来纠正它?

最佳答案

您已在 String 实例上定义了函数,因此:

def check(key)
    puts case
         when key.is_i?
           "Could be a number"
         when key.is_path?
           "This is a path"
         else
           "Ok"
         end
end

def check(key)
    puts case key
         when ->(s) { s.is_i? }
           "Could be a number"
         when ->(s) { s.is_path? }
           "This is a path"
         else
           "Ok"
         end
end

UPD 另请注意,我删除了对 puts 的多余后续调用。

关于ruby - 如何在 Ruby 中为 String 类创建新函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33373869/

相关文章:

ruby - 获取 sinatra 应用程序以从虚拟机提供服务

ruby-on-rails - Rails 4 View 渲染非常慢

ruby-on-rails - Rails教程对Rspec的误解

ruby - 续集将 "returning null"添加到我的插入内容中。我该如何禁用它?

arrays - 用另一个数组的元素替换数组中的 nils 的最佳方法

ruby "Mail" gem 文档

ruby-on-rails - 使用类方法启动工厂女孩

ruby-on-rails - 尝试安装 RVM 并获取 : Error running '__rvm_make -j2'

ruby - 生成源映射时出错 - grunt 和 sass 配置

ruby - "Errno::EACCESS...permission denied"运行 compass watch