¥È¥Ã¥×   ¿·µ¬ °ìÍ÷ ñ¸ì¸¡º÷ ºÇ½ª¹¹¿·   ¥Ø¥ë¥×   ºÇ½ª¹¹¿·¤ÎRSS

Ruby/¥µ¥ó¥×¥ë ¤Î¥Ð¥Ã¥¯¥¢¥Ã¥×¥½¡¼¥¹(No.3)

[[Ruby]]

#contents

*¥µ¥ó¥×¥ë [#g29f5ecf]
**Hello, world!¥á¥½¥Ã¥ÉÈÇ [#x79b06c8]
hello.rb
 def hello(name = "world")
   print "Hello, ", name, "!\n"
 end
 hello("Ruby")

**Hello, world!¥é¥¤¥Ö¥é¥êÈÇ [#x79b06c8]
helloLib.rb
 def hello(name = "world")
   print "Hello, ", name, "!\n"
 end

hello.rb
 require "helloLib"
 hello("Ruby")

-¥é¥¤¥Ö¥é¥ê¤ÏÊÌ¥Õ¥¡¥¤¥ë¤ÇºîÀ®¤·¡¢require ""¤ÇÆɤ߹þ¤ß¤Þ¤¹¡£
-¥é¥¤¥Ö¥é¥êÆâ³°¤ÇÍøÍѤǤ­¤ë¥°¥í¡¼¥Ð¥ëÊÑ¿ô¤Ï¡¢¡Ö$ÊÑ¿ô̾¡×¤È¤·¤Þ¤¹¡£

**Hello, world!¥¯¥é¥¹ÈÇ [#r58490cc]
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_reader :name|»²¾È¤Î¤ß²Äǽ|
|attr_write :name|Êѹ¹¤Î¤ß²Äǽ|
|attr_accessor :name|»²¾È¤ª¤è¤ÓÊѹ¹²Äǽ|
attr_accessor¤ÇÄêµÁ¤¹¤ë¤È¡¢¼¡¤Î¥á¥½¥Ã¥É¤òÄêµÁ¤·¤¿¤³¤È¤Ë¤Ê¤ê¤Þ¤¹¡£
 def name
   return @name
 end
 
 def name=(value)
   @name = value
 end

**ÇÛÎó [#k347a635]
 arLanguage = ["Ruby", "PHP", "C", "java"]
 arLanguage.each { |value|
   puts value
 end

**grep¥³¥Þ¥ó¥É [#k25a7ad1]
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ʸ ʸ»úÎó°ìÃ× [#c09a7661]
 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ʸ Àµµ¬É½¸½ [#m611e9ff]
 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ʸ ¥ª¥Ö¥¸¥§¥¯¥È¼±ÊÌ [#dcac99ac]
 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)¡×¤È¤¤¤Ã¤¿Èæ³Ó¤¬¹Ô¤¨¤Þ¤¹¡£