我只是在学习ruby,并希望将以下函数转换为来自php的ruby
function stringToDigits($str)
{ $str = strtolower($str);
$from = 'abcdefghijklmnopqrstuvwxyz';
$to = '22233344455566677778889999';
return preg_replace('/[^0-9]/', '', strtr($str, $from, $to));
}
我为之前没有正确解释而道歉。这是我的第一个问题......
我在将其转换为ruby时遇到问题。这就是我所做的
class String
def str_to_digits str
str = str.downcase
from = 'abcdefghijklmnopqrstuvwxyz'
to = '22233344455566677778889999'
self.gsub('/[^0-9]', '')
# here I am having problem to translate the whole string 'str' from 'from' to 'to'
# I dont know how to write it in ruby
end
end
答案 0 :(得分:0)
您可以使用String#tr(from, to)
文档:http://ruby-doc.org/core-2.0/String.html#method-i-tr
但是,您现在正在为字符串创建实例方法。你会这样称呼它:
"examplestring".str_to_digits("second examplestring")
但是你只需要一个字符串,所以你有三个选择:
class String
FROM = 'abcdefghijklmnopqrstuvwxyz'
TO = '22233344455566677778889999'
def instance_str_to_digits
return self.downcase.gsub(/\d/, '').tr(FROM, TO)
end
def destructive_instance_str_to_digits!
self.downcase!
self.gsub!(/\d/, '')
self.tr!(FROM, TO)
end
def self.class_str_to_digits(str)
return str.downcase.gsub(/\d/, '').tr(FROM, TO)
end
end
# calling the methods:
str = "examplestring"
result_1 = str.instance_str_to_digits
result_2 = String.class_str_to_digits(str)
str.destructive_instance_str_to_digits! # result overrides str