LoginSignup
2
2

More than 5 years have passed since last update.

ruby勉強メモ

Last updated at Posted at 2015-04-21

シンタックスシュガー

四則演算の+もメソッドであるから

syntax_sugar.rb

#メソッドのように書くと
1.+(1)

#シンタックスシュガー(通常このように書く)
1+1

メソッドチェーン

メソッドをつなげて書くことができる

method_chain.rb

#Stringのメソッド一覧を表示
"test".methods

#=>

<=>
==
===
eql?
hash
casecmp
+
*


#メソッドチェーン
"test".methods.size
#=>161

デバッグ

debag.rb

#クラス名を確認する方法
object.class

#クラスのメソッド一覧を表示
object.methods


#Arrayクラスの要素数を返す
array.size


#オブジェクトの中身を確認
require 'pp'
pp object

クラス

インスタンス変数とsetter,getterを書くと以下のようになる。

book.rb
class Book

  # インスタンス変数
  def author
    @author
  end

  def title
    @title
  end

  def isbn
    @isbn
  end


  # setter
  def author=(author)
    @author = author
  end

  def title=(title)
    @title = title
  end

  def isbn=(isbn)
    @isbn = isbn
  end

  def get_author
    author
  end

  # getter
  def get_title
    title
  end

  def get_isbn
    isbn
  end

end
class.rb
require_relative 'book.rb'
book = Book.new

# セット
book.author = 'aiueo'
book.title = 'akstn'

book.isbn = 123456

p book
#=> #<Book:0x007fa69488d730 @author="aiueo",@title="akstn", @isbn=123456>

p book.getAuthor
#=> "aiueo"

p book.getTitle
#=> "aiueo"

p book.getIsbn
#=> 123456

attr_accessor

getter setterを自動で設定してくれる

book.rb
class Book
  #setter getter設定
  attr_accessor :author, :title, :isbn
end
class.rb
require_relative 'book.rb'
book = Book.new

book.author = 'aiueo'
book.title = 'akstn'
book.isbn = 1234
p book
#=> #<Book:0x007f8c528fd6e0 @author="aiueo", @title="akstn", @isbn=1234>

p book.author
#=> "aiueo"

p book.title
#=> "akstn"

p book.isbn
#=> 1234

initialize

book.rb
class Book

  #setter getter設定
  attr_accessor :author, :title, :isbn

  #コンストラクタ(インスタンス作成時代入を行う)
  def initialize(author, title)
    @author = author
    @title = title
  end
end
class.rb
require_relative 'book.rb'
book = Book.new('author', 'title')
p book
#=> #<Book:0x007f7ff281e948 @author="author", @title="title">
2
2
4

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
2
2