ミームの死骸を待ちながら

We are built as gene machines and cultured as meme machines, but we have the power to turn against our creators. We, alone on earth, can rebel against the tyranny of the selfish replicators. - Richard Dawkins "Selfish Gene"

We are built as gene machines and cultured as meme machines, but we have the power to turn against our creators.
We, alone on earth, can rebel against the tyranny of the selfish replicators.
- Richard Dawkins "Selfish Gene"

RubyでFizzBuzzかけたよ!+いろいろ考えてみた

404 Blog Not Found:やる気ってどこでやる気?
経由で見つけた↓の記事。


1から100までの数をプリントするプログラムを書け。ただし3の倍数のときは数の代わりに「Fizz」と、5の倍数のときは「Buzz」とプリントし、3と5両方の倍数の場合には「FizzBuzz」とプリントすること。

ちゃんとしたプログラマであれば、これを実行するプログラムを2分とかからずに紙に書き出せるはずだ。怖い事実を聞きたい? コンピュータサイエンス学科卒業生の過半数にはそれができないのだ。自称上級プログラマが答えを書くのに10-15分もかかっているのを見たこともある。

どうしてプログラマに・・・プログラムが書けないのか?


こんなこと書いてて怖かったので、RubyFizzBuzz書いてみた。Moduloが「%」であることを忘れてて所要時間4分20秒。かかりすぎ…。

for i in 1..100 do
  if i % 3 == 0
    if i % 5 == 0
      puts "FizzBuzz"
    end
    puts "Fizz"
  elsif i % 5 == 0
    puts "Buzz"
  else 
    puts i  
  end
end


というか適当すぎるな。あまりにアレなのでもう少し考えて、Kiyoyaに倣って(コードを見たことはないけど)三項演算子を使って一行で書いてみた。

for i in 1..100  do  i % 15 == 0 ? puts "FizzBuzz" : i % 3 == 0 ? puts "Fizz" : i % 5 == 0 ? puts "Buzz" : puts i ) end 


としたら

parse error, unexpected tSTRING_BEG, expecting kDO or '{' or '('


というエラーがでる??そこで

for i in 1..100  do puts( i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : i ) end 


このようにしたところ、うまく動作した。あえて一行で書いたけど、


三項演算子を使うときは、条件はどんなに短くても必ずカッコで囲って、先頭に持ってくるようにしている。
条件をカッコで囲うだけでも、かなり読みやすくなる気がする。

最速インターフェース研究会 :: 三項演算子の正しい書き方ってあるのだろうか

このような記述を見つけたので適用してみると

for i in 1..100  do
  puts((i % 15 == 0) ? "FizzBuzz" :
  (i % 3 == 0 ) ? "Fizz" :
  (i % 5 == 0 ) ? "Buzz" :
  i)
end

こうなろうか。うーん…それにしてもputs入れちゃだめなのか。三項演算子は純粋にIF文と等しい意味ではないようだ。不思議だったのでProgramming Ruby: The Pragmatic Programmer's Guideを調べてみた。

... for the C fans out there, Ruby also supports the C-style conditional expression.

cost = song.duration > 180 ? 0.35 : 0.25

A conditional expression returns the value of either the expression before or the expression after the colon, depending on whether the boolean expression before the question mark evaluates to true or false. In this state, if the song duration is greater than three minutes, the expression returns 0.35. For shorter songs, it returns 0.25. Whatever the result, it is then assigned to cost.


from Programming Ruby: The Pragmatic Programmer's Guide, p.97


確かに、puts "hogehoge"という文章はcostという変数に代入したりできない。"returns"...「値を返す」ってそういう意味ですか。正式な用語ではこの規定をどう説明すればいいのだろう。


そうだ、一行で書いたFizzBuzzは詰めに詰めて計76文字でした。これ、もっと短くできる人居たら教えてくれませんか?

for i in 1..100 do puts(i%15==0?"FizzBuzz":i%3==0?"Fizz":i%5==0?"Buzz":i)end

Programming Ruby: The Pragmatic Programmer's Guide

Programming Ruby: The Pragmatic Programmer's Guide