5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【備忘録】Ruby ワンライナー(1行)でメソッド定義

Last updated at Posted at 2017-08-26
# クラスメソッドを定義
class TestData
  class << self

    # 一般的なメソッド定義
    def hoge1
        "hoge1"
    end
    
    # 1行でメソッド定義(文字列を返す)
    def hoge2() "hoge2"  end
    define_method(:hoge3) { "hoge3" }
    
     # 1行でメソッド定義(ハッシュを返す)
    def hoge4() { foo: "foo", bar: "bbb" } end
    define_method(:hoge5) { { foo: "foo", bar: "bbb" } }
    
  end
end

# メソッドを呼び出す
puts TestData.hoge1 # => hoge1

puts TestData.hoge2 # => hoge2
puts TestData.hoge3 # => hoge3

puts TestData.hoge4[:foo] # => foo
puts TestData.hoge5[:foo] # => foo
5
2
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?