gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:44:38 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com