技術メモ

主にRuby関連

Cool!!な回答集 in 「rubeque」 (http://www.rubeque.com/)

Rubeque』で Cool!! だったから score += 1 した回答集

正規表現がCool!!

# 19 	Separating Numbers with Commas
def separate_with_comma(n)
  n.to_s.gsub(/(?<=\d)(?=(\d{3})+$)/,',')
end

# assert_equal         "1", 
p separate_with_comma(1)
# assert_equal        "10", 
p separate_with_comma(10)
# assert_equal       "100", 
p separate_with_comma(100)
# assert_equal     "1,000", 
p separate_with_comma(1000)
# assert_equal    "10,000", 
p separate_with_comma(10000)
# assert_equal   "100,000", 
p separate_with_comma(100000)
# assert_equal "1,000,000", 
p separate_with_comma(1000000)

with_objectが分かってなかった。条件外の時にわざわざnilを返して最後にcompactしちゃった。

# 22 	Each With Object
def even_sum(arr)
  arr.each_with_object([]){|i,r| r << i.reverse if i && i.size.even? }
end

p even_sum(["cat", "dog", "bird", "fish"]) #, ["drib", "hsif"]
p even_sum(["why", "chunky", nil, "lucky", "stiff"]) #, ["yknuhc"]
p even_sum(["rewsna", "hitch hiker", "si", "guide", "galaxies ", "24"]) #, ["answer", "is", "42"]

Cool!!ってよりは何コレ?!スゴイ!!これがフィボナッチ??

# 24 	Your Favorite and Mine, Fibonacci!
def fibo_finder(n)
  root5 = Math.sqrt(5)
  phi = 0.5 + root5 / 2
  Integer(0.5 + phi**n / root5)
end

#assert_equal 0, 
p fibo_finder(0)
#assert_equal 1, 
p fibo_finder(1)
#assert_equal 3, 
p fibo_finder(4)
#assert_equal 13, 
p fibo_finder(7)
#assert_equal 55, 
p fibo_finder(10)