ruby 编写一个方法separate_comma,它以整数作为输入,并以逗号分隔的整数作为字符串返回

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 编写一个方法separate_comma,它以整数作为输入,并以逗号分隔的整数作为字符串返回相关的知识,希望对你有一定的参考价值。


#######################################PSEUDOCODE###################################

# INPUT: a positive integer number formatted without commas
# OUPUT: the input number formatted with commas as a string
# [refactored solution]
# Convert the input number to string
# Reverse the string
# put a comma after each complete group of 3 characters
# reverse and return the string

###################################INITIAL CODE#####################################

def separate_comma(number)
  number.to_s.split(//).reverse.each_slice(3).map(&:join).join(',').reverse
end

####################################REFACTORED CODE#################################

def separate_comma(number)
   number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\1,').reverse
end

###################################DRIVER CODE######################################

##ATTEMPT1-DRIVER CODE DOESN'T WORK
def random_num(min, max)
  rand(max - min + 1) + min
end
#create a random number and use the exact tests from the rspecs on socrates
num1 = random_num(0,999)
num2 = random_num(1000,999999)
num3 = random_num(1000000,999999999)
#Doesn't work for num2 or num3 I'm thinking because of the commas the he regex 
#Not sure how to fix it-anyone?
puts separate_comma(num1) == num1.to_s[/^\d{1,3}$/] #passes
puts separate_comma(num2) == num2.to_s[/^\d{1,3},\d{3}$/] #fails
puts separate_comma(num3) == num3.to_s[/^\d{1,3},\d{3},\d{3}$/] #fails

##ATTEMPT2-WORKS
puts separate_comma(123543234532) == "123,543,234,532"
puts separate_comma(234234523452346345653) == "234,234,523,452,346,345,653"
puts separate_comma(14321435) == "14,321,435"

###################################REFLECTION#######################################

# INCLUDE REFLECTION HERE: My first attempt here was really more of deciphering
# how the code worked--I combimed some methods I found online and it passed--but
# I wasn't really sure what was going on. Sometimes disecting code helps me gain
# a better picture around all teh different uses for commonly used methods. I
# realized it wasn'ta  very efficient or elegant solution and thought about what
# I could do to refactor it. it took me a while to realize that ruby regex and
# strings use the \ to reference matched groups, I was trying all sorts of
# things related to `$`. I learned a bit about regex and its power, which I then
# expanded further in the next challenge.

# The failure of my first driver code is still unclear to me. I would love some
# input from someone!

以上是关于ruby 编写一个方法separate_comma,它以整数作为输入,并以逗号分隔的整数作为字符串返回的主要内容,如果未能解决你的问题,请参考以下文章

在编写rspec测试用例时如何覆盖ruby方法的局部变量?

我在哪里可以编写要在部分中使用的方法? (Ruby on Rails)

基本 Ruby - 编写哈希 [重复]

在 Ruby 中使用 2 个助手构建函数的惯用方法

Ruby元编程

如何在 Ruby 中使用 Where 子句 (PostgreSQL) 中的变量编写查询