LoginSignup
0
1

More than 5 years have passed since last update.

Ruby初心者で勉強中に気になる点

Posted at

今回「たのしいRuby」の本を読んで、他の言語と比べながら、気になる点をメモします。

インスタンス作成のnewメソッド

javaみたいにnewキーワードを利用するではなく、クラスのnewメソッドを使います。より自然だと思います。

class Cat
  def initialize(name, color)
    puts "initialize called!"
    @name = name; @color = color
  end
end

cat = Cat.new("Tama", "white")

例外処理のretry

javaの例外処理機構と比べると、リトライしたい時の処理ロジックがより簡単になります。

10.times do |i|
  retry_counter = 0
  begin
    raise
  rescue
    retry_counter += 1
    if retry_counter <= 5
      puts i.to_s + ": retry"
      retry
    else
      puts "retried 5 times so go to next loop"
      next
    end
  end
end

reduceメソッド

一見reduceメソッドがないようですが、ネットで調べたら、勿論ありました。

numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
numbers.reduce{ | sum, n | sum + n }  #=> 55

配列の範囲操作が気楽

alpha = ["a", "b", "c", "d", "e"]
p alpha[1..3]  #=> ["b", "c", "d"]

ファイル操作機能が豊富

ファイルの読み書きだけでなく、ファイルやディレクトリのコピーや移動も簡単に実装できます。

参考

rescue 節で一定回数 retry したあとは次に移るループ

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1