開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 7章(フロー制御), 7.5(練習問題)耳の遠いおばあちゃん を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
耳の遠いおばあちゃん
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby1.9 #-*- coding: utf-8 -*- while true said = gets.chomp if said == 'BYE' puts 'BYE' break elsif said == said.upcase puts "NO, NOT SINCE #{1930 + (rand 21)}!" else puts "HUH?! SPEAK UP, SPNNY!" end end
入出力結果(Terminal)
$ ./sample.rb hi HUH?! SPEAK UP, SPNNY! Hi HUH?! SPEAK UP, SPNNY! HI NO, NOT SINCE 1931! HI NO, NOT SINCE 1942! HI NO, NOT SINCE 1946! HI NO, NOT SINCE 1940! HI NO, NOT SINCE 1930! bye HUH?! SPEAK UP, SPNNY! Bye HUH?! SPEAK UP, SPNNY! BYE BYE $
ちなみにJavaScriptの場合。
コード(BBEdit)
<pre id='pre0' ></pre> <div id="d0"> <label>話しかける: <input id="t0" type="text" value="Hi" /></label> <input id="b0" type="button" value="say" /> </div> <script> function clicked(){ var said = $('#t0').val(); $('#pre0').append(said + "\n"); if (said === "BYE") { $('#pre0').append("BYE!\n"); $('#d0').remove(); return; } else if (said === said.toUpperCase()) { $('#pre0').append("NO, NOT SINCE " + (1930 + Math.floor(21 * Math.random())) + "!\n"); } else { $('#pre0').append("HUH?! SPEADK UP, SONNY!\n"); } } $('#b0').click(clicked); $('#t0').keydown(function( e ) { var e = e ? e : window.event; if(e.keyCode === 13 ) { clicked(); } }); </script>
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- print("5 bottles of beer on the wall, 5 bottles of beer!") for i in range(4, 1, -1): print("Take one down, pass it around, {0} bottles of beer on the wall!".format(i)) print("{0} bottles of beer on the wall, {0} bottles of beer!".format(i)) print("Take one down, pass it around, 1 bottle of beer on the wall!") print("1 bottle of beer on the wall, 1 bottle of beer!") print("Take one down, pass it around, no more bottles of beer on the wall!")
入出力結果(Terminal)
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- import random while True: said = input() if said == 'BYE': print("BYE") break elif said == said.upper(): print("NO, NOT SINCE {0}!".format(random.randint(1930, 1950))) else: print("HUH?! SPEAK UP, SPNNY!")
perlの場合。
sample.pl
コード(BBEdit)
#!/usr/bin/env perl use strict; use warnings; use utf8; use 5.016; binmode STDIN, ":utf8"; binmode STDOUT, ":utf8"; use POSIX; while (1) { chomp(my $said = <STDIN>); if ($said eq 'BYE') { print "BYE!\n"; last; } elsif ($said eq uc $said) { print "NO, NOT SINCE ", 1930 + floor(rand 21), "\n"; } else { print "HUH?! SPEAK UP, SPNNY!\n"; } }
入出力結果(Terminal)
$ ./sample.pl hi HUH?! SPEAK UP, SPNNY! Hi HUH?! SPEAK UP, SPNNY! HI NO, NOT SINCE 1932 HI NO, NOT SINCE 1939 HI NO, NOT SINCE 1932 HI NO, NOT SINCE 1933 HI NO, NOT SINCE 1935 HI NO, NOT SINCE 1946 BYE BYE! $
0 コメント:
コメントを投稿