Rubyでコンソールにy/nを入力させて、対話的に処理する


スポンサーリンク

ハッシュ

ハッシュはハッシュテーブルデータ構造を基礎にしている。
任意のキーオブジェクトを値オブジェクトにマッピングする。

# -*- coding: UTF-8 -*-

hash = {
	:one => 1,
	:two => 2
}

puts hash[:one] #1
hash[:three] = 3

hash.each do |key, value|
	print "#{value}:#{key};" #1:one;2:two;3:three;
end

Rubyでyes/noの対話

def are_you_ok?
	while true
		print "is it ok? [y|n]:"
		response = gets
		case response
		when /^[yY]/
			puts "you say yes!"
			return true
		when /^[nN]/, /^$/
			puts "you say no!"
			return false
		end
	end	
end

are_you_ok?

結果

C:\samples\ruby>ruby sample.rb
is it ok? [y|n]:b
is it ok? [y|n]:a
is it ok? [y|n]:s
is it ok? [y|n]:
you say no!