How to pass a local Ruby variable from a method to a sub-method?

Given this simple Ruby code:

def testMethod
  testVar = 1
  def subTestMethod
    if testVar == 1
      puts 'Yes'
    else
      puts 'No'
    end
  end
  subTestMethod
end

testMethod

Is there a way to pass a local variable testVarinto a sub-method without having to use a class variable?

+3
source share
3 answers

The code you have will most likely not do what you want:

Internal defin your code does not define a local method. Instead, it defines it subTextMethodas the global method in the class Object, as soon as it testMethodis called for the first time. This means that after calling testMethod, you can call subTestMethodfrom anywhere.

, subTestMethod testMethod, , , subTestMethod testMethod.

, ​​ ( , ):

def testMethod
  testVar = 1
  subTestLambda = lambda do
    if testVar == 1
      puts 'Yes'
    else
      puts 'No'
    end
  end
  subTestLambda.call
end
+8

Ruby ( -). , :

def testMethod
  testVar = 1
  Object.send(:define_method, :subTestMethod) do
    if testVar == 1
      puts 'Yes'
    else
      puts 'No'
    end
  end
  subTestMethod
end

testMethod

, , , , , , , , , , .

: () snake_case, , .

, testMethod, subTestMethod testVar test_method, sub_test_method test_var. define_method sub_test_method. puts if, , , , , :

def test_method
  test_var = 1

  Object.send(:define_method, :sub_test_method) do
    puts(if test_var == 1 then 'Yes' else 'No' end)
  end

  sub_test_method
end

test_method

, , , :

def test_method
  test_var = 1

  sub_test_lambda = -> { puts(if test_var == 1 then 'Yes' else 'No' end) }

  sub_test_lambda.()
end

test_method
+5

Pass testVaras parametersubTestMethod

def testMethod
  testVar = 1
  def subTestMethod(testVar)
    if testVar == 1
      puts 'Yes'
    else
      puts 'No'
    end
  end
  subTestMethod testVar
end
+1
source

Source: https://habr.com/ru/post/1782835/


All Articles