Ruby/¥µ¥ó¥×¥ë
Last-modified: 2018-11-14 (¿å) 15:24:01 (2642d)
¥µ¥ó¥×¥ë †
Hello, world!¥á¥½¥Ã¥ÉÈÇ †
hello.rb
def hello(name = "world")
print "Hello, ", name, "!\n"
end
hello("Ruby")
DOS¥×¥í¥ó¥×¥È¤«¤é¼Â¹Ô¤¹¤ëÊýË¡
>ruby hello.rb
¢¨¤¢¤é¤«¤¸¤áruby.exe¤Ë¥Ñ¥¹¤òÄ̤·¤Æ¤ª¤¤Þ¤¹¡£
Hello, world!¥é¥¤¥Ö¥é¥êÈÇ †
helloLib.rb
def hello(name = "world") print "Hello, ", name, "!\n" end
hello.rb
require "helloLib"
hello("Ruby")
- ¥é¥¤¥Ö¥é¥ê¤ÏÊÌ¥Õ¥¡¥¤¥ë¤ÇºîÀ®¤·¡¢require ""¤ÇÆÉ¤ß¹þ¤ß¤Þ¤¹¡£
- ¥é¥¤¥Ö¥é¥êÆâ³°¤ÇÍøÍѤǤ¤ë¥°¥í¡¼¥Ð¥ëÊÑ¿ô¤Ï¡¢¡Ö$ÊÑ¿ô̾¡×¤È¤·¤Þ¤¹¡£
Hello, world!¥¯¥é¥¹ÈÇ †
HelloWorld.rb
class HelloWorld
def initialize(name = "world")
@name = name;
end
def hello
print "Hello, ", name, "!\n"
end
end
hello.rb
require "HelloWorld"
ruby = HelloWorld.new("Ruby")
world = HelloWorld.new
ruby.hello
world.hello
- Äê¿ô¤Ï²¿¤âÉÕ¤±¤º¡ÖVERSION = 1¡×¤Ê¤É¤ÈÄêµÁ¤·¤Æ¡¢¡ÖHelloWorld::VERSION¡×¤È¤¤¤¦É÷¤ËÍøÍѤ·¤Þ¤¹¡£
- ¥¯¥é¥¹ÊÑ¿ô¤Ï¡Ö@@var = 0¡×¤Ê¤É¤ÈÄêµÁ¤·¤Æ¡¢³°¤«¤éÍøÍѤ¹¤ë¾ì¹ç¤Ï¡¢¥á¥½¥Ã¥É¤òºîÀ®¤·¤Æ¥¢¥¯¥»¥¹¤·¤Þ¤¹¡£
- ¥¯¥é¥¹¥á¥½¥Ã¥É¤Ï¡Ödef HelloWorld.hello(name)¡×¤Ê¤É¤ÈÄêµÁ¤·¤Æ¡¢³°¤«¤éÍøÍѤ¹¤ë¾ì¹ç¤Ï¡¢¡ÖHelloWorld.hello("world")¡×¤È¤¤¤¦É÷¤ËÍøÍѤ·¤Þ¤¹¡£
- ¥¯¥é¥¹¤Î¥¤¥ó¥¹¥¿¥ó¥¹ÊÑ¿ô¤Ï¡Ö@¡×¤Ç»Ï¤Þ¤ê¤Þ¤¹¡£
- ¼¡¤ÎÄêµÁ¤ò¹Ô¤¦¤È¡¢¥¯¥é¥¹¤Î³°¤«¤é¥¤¥ó¥¹¥¿¥ó¥¹ÊÑ¿ô@name¤Ë¥¢¥¯¥»¥¹¤Ç¤¤Þ¤¹¡£
attr_accessor¤ÇÄêµÁ¤¹¤ë¤È¡¢¼¡¤Î¥á¥½¥Ã¥É¤òÄêµÁ¤·¤¿¤³¤È¤Ë¤Ê¤ê¤Þ¤¹¡£
attr_reader :name »²¾È¤Î¤ß²Äǽ attr_write :name Êѹ¹¤Î¤ß²Äǽ attr_accessor :name »²¾È¤ª¤è¤ÓÊѹ¹²Äǽ def name return @name end def name=(value) @name = value end
ÇÛÎó †
arLanguage = ["Ruby", "PHP", "C", "java"]
arLanguage.each { |value|
puts value
end
grep¥³¥Þ¥ó¥É †
grepr.rb
pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
file = open(filename)
while line = file.gets
if pattern =~ line
print line
end
end
file.close
¼Â¹ÔÊýË¡
ruby grepr ¥Ñ¥¿¡¼¥ó ¥Õ¥¡¥¤¥ë̾
case - whenʸ ʸ»úÎó°ìÃ× †
arTag = ["a", "img", "pre"]
arTag.each { |tag|
case tag
when "p", "a", "i", "b", "blockquote"
print tag, " has child.\n"
when "img", "br"
print tag, " has no child.\n"
else
print tag, " cannot be used.\n"
end
}
case - whenʸ Àµµ¬É½¸½ †
while line = gets
case line
when /^From:/i
puts "find sender!"
when /^To:/i
puts "find receiver!"
when /^Subject:/i
puts "find subject!"
when /^$:/
puts "finish!"
else
## ÆÉ¤ßÈô¤Ð¤¹
end
end
case - whenʸ ¥ª¥Ö¥¸¥§¥¯¥È¼±ÊÌ †
arObject = ["a", 1, nil]
arObject.each { |item|
case item
when String
puts "item is String."
when Numeric
puts "item is Numeric."
else
puts "item is something."
end
}
- ¡Öif item.instance_of?(String)¡×¤È¤¤¤Ã¤¿Èæ³Ó¤¬¹Ô¤¨¤Þ¤¹¡£
¥Ð¥¤¥Ê¥ê¥Õ¥¡¥¤¥ëÆþÎÏ
#pre{{
fp = open("./hoge")
fp.binmode
while(buf = fp.read(4))
#É乿ÉÕ32bit¡Ê4¥Ð¥¤¥È¡Ëint·¿¤Ç²ò¼á
iTmp = buf.unpack("i*")
print iTmp
end
}}
Web¤ËÇÛÃÖ¤µ¤ì¤¿¥Õ¥¡¥¤¥ë¤òÆÉ¤ß¹þ¤ß¥³¥ó¥½¡¼¥ë¤Ë½ÐÎϤ¹¤ë¥µ¥ó¥×¥ë
sample_open_uri.rb
# Web¤ËÇÛÃÖ¤µ¤ì¤¿¥Õ¥¡¥¤¥ë¤òÆÉ¤ß¹þ¤ß¥³¥ó¥½¡¼¥ë¤Ë½ÐÎϤ¹¤ë¥µ¥ó¥×¥ë
require 'open-uri'
open('http://www.google.co.jp/') do |fpWeb|
fpWeb.each do |line|
puts line
end
end