Little by little output of what I learned through the recently started Codewar
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
#My answer
def createPhoneNumber(numbers)
return "(#{numbers[0]}#{numbers[1]}#{numbers[2]}) #{numbers[3]}#{numbers[4]}#{numbers[5]}-#{numbers[6]}#{numbers[7]}#{numbers[8]}#{numbers[9]}"
end
#Ideal answer
def createPhoneNumber(str)
"(#{str[0..2].join}) #{str[3..5].join}-#{str[6..10].join}"
end
https://docs.ruby-lang.org/ja/latest/method/Array/i/join.html
In the code I wrote, the array data is foolishly and carefully expanded character by character.
In the ideal code, it is done like str [0..2]
, and the join method
is used to combine the elements of the array and convert them into one string.
Recommended Posts