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

Ruby/¥µ¥ó¥×¥ë ¤Î¥Ð¥Ã¥¯¥¢¥Ã¥×(No.4)


Ruby

¥µ¥ó¥×¥ë

Hello, world!¥á¥½¥Ã¥ÉÈÇ

hello.rb

def hello(name = "world")
  print "Hello, ", name, "!\n"
end
hello("Ruby")

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_reader :name»²¾È¤Î¤ß²Äǽ
    attr_write :nameÊѹ¹¤Î¤ß²Äǽ
    attr_accessor :name»²¾È¤ª¤è¤ÓÊѹ¹²Äǽ
    attr_accessor¤ÇÄêµÁ¤¹¤ë¤È¡¢¼¡¤Î¥á¥½¥Ã¥É¤òÄêµÁ¤·¤¿¤³¤È¤Ë¤Ê¤ê¤Þ¤¹¡£
    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
}}