-1

我只是在学习 ruby​​,想将下面的函数从 php 转换为 ruby

function stringToDigits($str)
 {  $str = strtolower($str);
    $from = 'abcdefghijklmnopqrstuvwxyz';
    $to = '22233344455566677778889999';
    return preg_replace('/[^0-9]/', '', strtr($str, $from, $to));
 }

对于之前没有正确解释,我深表歉意。这是我的第一个问题......

我在将其转换为红宝石时遇到问题。这就是我所做的

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
4

1 回答 1

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
于 2013-03-14T23:34:48.363 回答