Project

General

Profile

Actions

Feature #10571

closed

Keyword arguments with local variable

Added by gogotanaka (Kazuki Tanaka) over 9 years ago. Updated over 9 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:66716]

Description

It's kind of curiosity. As far as I searched, I couldn't get sensible reason.
Please give me information if you have free time.

class MyClass
  var = 'test'
  def my_method(kwd_var: var)
    p kwd_var
  end
end

MyClass.new.my_method
#=> NameError: undefined local variable or method `var' for #<MyClass:0x007f91520a15c8>

I've expected above code is same as below code.

class MyClass
  def my_method(kwd_var: 'test')
    p kwd_var
  end
end

MyClass.new.my_method
#=> "test"

Take your time. Thanks.

Updated by gogotanaka (Kazuki Tanaka) over 9 years ago

Ops.. not only Keyword arguments also other arguments with default value has same behavior.

I suppose there must be sensible reason for that, I need to look for more.. sorry for noisey then.

Updated by matz (Yukihiro Matsumoto) over 9 years ago

var is a local variable in the class scope, which cannot be accessed from the method. a method has independent scope.

Matz.

Updated by matz (Yukihiro Matsumoto) over 9 years ago

  • Status changed from Open to Closed

Updated by nobu (Nobuyoshi Nakada) over 9 years ago

You can define a method shares the scope with the outside by define_method.

Updated by gogotanaka (Kazuki Tanaka) over 9 years ago

@Yukihiro Matsumoto san
Thank you so much. It does make sense, I need to more deepen understanding your language.

@Nobuyoshi Nakada san
Thank you for your information. I think define_method, moreover block is really really awesome.

Sorry for the noise.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0