一个异常(exception)是返回的字符串不能以连字符开头或结尾,并且每个奇数数字前后只允许有一个单个连字符。例如:
def hyphenate(number)
# code
end
hyphenate(132237847) # should return "1-3-22-3-7-84-7"
"-1-3-22-3-7-84-7-" # incorrect because there is a hyphen before and after
# each beginning and ending odd digit respectively.
"1--3-22-3--7-84-7" # Also incorrect because there is more than one
# single hyphen before and after each odd digit
最佳答案
我建议匹配一个非单词边界 \B
(这将匹配两个数字之间的位置) 后面或前面有一个奇数:
number.to_s.gsub(/\B(?=[13579])|\B(?<=[13579])/, '-')
由于相同的位置不能匹配两次,因此避免了连续连字符的问题。
关于ruby - 如何编写一个方法,它接受一个数字并返回一个字符串,在每个奇数之前和之后放置一个连字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459441/