0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

refine、using メソッド

Posted at

refine、usingを使うと独自の変更の有効範囲(スコープ)を限定することができます

irb(main):001* module SpringShuffle
irb(main):002*   refine String do # refineメソッドを使ってrefinementsを適用するクラスを指定する
irb(main):003*     def shuffle
irb(main):004*       chars.shuffle.join
irb(main):005*     end
irb(main):006*   end
irb(main):007> end
=> #<refinement:String@SpringShuffle>

userクラスのインスタンスが使うとエラーになる

irb(main):018* class User
irb(main):019*   using SpringShuffle # usingメソッドでrefinementsを有効にする
irb(main):020*
irb(main):021*   def initialize(name)
irb(main):022*     @name = name
irb(main):023*   end
irb(main):024*
irb(main):025*   def shuffled_name
irb(main):026*     @name.shuffle
irb(main):027*   end
irb(main):028> end
=> :shuffled_name
irb(main):029> user = User.new('Alice')
=> #<User:0x00000001094f83c8 @name="Alice">
irb(main):030> user.shuffled_name
=> "Aielc"
irb(main):031> 'Alice'.shuffle
(irb):31:in `<main>': undefined method `shuffle' for "Alice":String (NoMethodError)

using以降だと使える

irb(main):001* module StringShuffle
irb(main):002*   refine String do
irb(main):003*     def shuffle
irb(main):004*       chars.shuffle.join
irb(main):005*     end
irb(main):006*   end
irb(main):007> end
=> #<refinement:String@StringShuffle>
irb(main):008> puts 'Alice'.shuffle
(irb):8:in <main>': undefined method `shuffle' for "Alice":String (NoMethodError)

puts 'Alice'.shuffle

irb(main):009> using StringShuffle
=> main
irb(main):010> puts 'Alice'.shuffle
ceAli
=> nil

モジュールのメソッドを使うクラスを指定する

irb(main):008* module InterHello
irb(main):009*   refine Integer do
irb(main):010*     def hello
irb(main):011*       "hello"
irb(main):012*     end
irb(main):013*   end
irb(main):014> end
=> #<refinement:Integer@InterHello>
irb(main):015> 1.hello
(irb):15:in <main>': undefined method `hello' for 1:Integer (NoMethodError)

1.hello

irb(main):016> "1".hello
(irb):16:in <main>': undefined method `hello' for "1":String (NoMethodError)

"1".hello
   ^^^^^^

irb(main):017> using InterHello
=> main
irb(main):018> "1".hello
(irb):18:in <main>': undefined method `hello' for "1":String (NoMethodError)

"1".hello
   ^^^^^^

irb(main):019> 1.hello
=> "hello"

感想

refineで呼び出すクラスを指定して、usingでモジュールのメソッドの使用を許可する

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?