Studying at CodeWar

About this article

Little by little output of what I learned through the recently started Codewar

Learning ① join method

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

Commentary

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

Studying at CodeWar
Studying at CodeWar (ruby) ⑥ inject
Studying at CodeWar (ruby) ③ squeeze, gsub
Studying with CodeWar (ruby) ⑤ proc
Studying with CodeWar (ruby) ④ case ~ when
Studying Java ―― 3
Studying Java ―― 9
Studying Java ―― 4
Studying Java -5
Studying Java ―― 1
Studying Java # 0
Studying Java ―― 8
Studying Java ②
Studying Java ―― 7
Studying Java ―― 2
Studying Java ①
Studying Java -10