Ruby 如何编写一个方法,该方法接收一个数字并返回一个字符串,在每个奇数之前和之后放置一个连字符?
一个例外是,返回的字符串不能以连字符开头或结尾,并且每个奇数数字只允许在每个奇数数字之前和之后有一个单连字符。例如:Ruby 如何编写一个方法,该方法接收一个数字并返回一个字符串,在每个奇数之前和之后放置一个连字符?,ruby,regex,Ruby,Regex,一个例外是,返回的字符串不能以连字符开头或结尾,并且每个奇数数字只允许在每个奇数数字之前和之后有一个单连字符。例如: 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 #
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
返回“1-3-22-3-7-84-7”
返回“1-3-22-3-7-84-7”一种简单的方法是将数字转换为字符串,
string#split
奇数位上的字符串(使用一个组以便奇数位分隔符进入输出),清除string#split
将产生的零散的'
字符串,并将其与数组#join
组合在一起:
number.to_s.split(/([13579])/).reject(&:empty?).join('-')
一种简单的方法是将数字转换为字符串,
string#split
奇数位上的字符串(使用一个组以便奇数位分隔符进入输出),清理string#split
将产生的零散字符串,并将其与数组#join
重新组合:
number.to_s.split(/([13579])/).reject(&:empty?).join('-')
下面是另一种获取数字并以字符串形式返回的方法,其奇数由连字符包围:
def hyphenate(number)
result = ""
number.digits.reverse.each do |digit|
result << (digit.odd? ? "-#{digit}-" : digit.to_s)
end
result.gsub("--", "-").gsub(/(^-|-$)/, "")
end
hyphenate(132237847)
# => "1-3-22-3-7-84-7"
def连字符(数字)
result=“”
数字。数字。反转。每个do |数字|
结果“1-3-22-3-7-84-7”
希望有帮助 下面是另一种获取数字并以字符串形式返回的方法,其奇数由连字符包围:
def hyphenate(number)
result = ""
number.digits.reverse.each do |digit|
result << (digit.odd? ? "-#{digit}-" : digit.to_s)
end
result.gsub("--", "-").gsub(/(^-|-$)/, "")
end
hyphenate(132237847)
# => "1-3-22-3-7-84-7"
def连字符(数字)
result=“”
数字。数字。反转。每个do |数字|
结果“1-3-22-3-7-84-7”
希望有帮助 我建议匹配一个非单词边界\B
(它将匹配两个数字之间的位置),后面或前面跟一个奇数:
number.to_s.gsub(/\B(?=[13579])|\B(?<=[13579])/, '-')
number.to_.s.gsub(/\B(?=[13579])|\B(?我建议匹配非单词边界\B
(将匹配两位数字之间的位置),后面或前面带有奇数:
number.to_s.gsub(/\B(?=[13579])|\B(?<=[13579])/, '-')
number.to_.s.gsub(/\B(?=[13579])|\B(?如果你想减少标点符号,你可以使用n.to_i.odd?
而不是显式模数。如果你想减少标点符号,你可以使用n.to_i.odd?
而不是显式模数。@muistooshort:谢谢to_s,这是多么奇怪的行为。@muistooshort:谢谢to_s,这是多么奇怪的行为啊你也应该添加你尝试过的…你也应该添加你尝试过的。。。