про блок, yield
require_relative 'MyTest'
require_relative 'config'
p MyTest.extension
MyTest.rb
module MyTest
class << self
attr_accessor :extension
def config
yield self
endmy_proc= Proc.new {|msg| puts msg }
my_proc2= proc {|msg| puts msg }
my_lambda = lambda {|msg| puts msg }
my_lambda2 = ->(msg) {puts msg }
my_proc.call("hello")
my_proc2.call("hello mir")
my_lambda.call("hello cat")
my_lambda.call("hello dog")
end
end
config.rb
MyTest.config do |config|
config.extension = '.txt'
end
так как нам не нужно создавать экземпляр модуля, такое прокатывает. мы создаем синглтон класс для модуля, обращаемся к нему и передаем блок "config.extension = '.txt'" yield self - мы передаем выполняемый блок селф. то есть имя модуля MyTest.
способы вызова лямбы и прок
my_proc= Proc.new {|msg| puts msg }
my_proc2= proc {|msg| puts msg }
my_lambda = lambda {|msg| puts msg }
my_lambda2 = ->(msg) {puts msg }
my_proc.call("hello")
my_proc2.call("hello mir")
my_lambda.call("hello cat")
my_lambda.call("hello dog")
отличие прок и лямбды, число аргументов, rerurn
def testmethod(callable)
result = callable.call("hello")
puts "result = #{result}"
puts "inspect = #{callable.inspect}"
end
my_lambda = proc do |x| //для тестирования замени на lambda
puts x
return x
end
testmethod(my_lambda)
в lambda дополнительно выполняться puts "result = #{result}" puts "inspect = #{callable.inspect}"
прок не будет ругаться на лишние аргументы, лямбда будет ругаться на не верное количество переданных аргументов.
блок можно передавать 1, проков и лямбд хоть сколько, а дальше
# вариант 1, передаем в метод блок
def bloc_method
yield "hello test"
end
bloc_method do |msg|
puts msg
end
# вариант 1
# вариант 2 передаем в метод блок
def bloc_method2(&myblock)
myblock.call("hello wold")
end
bloc_method2 do |msg|
puts msg
end
# вариант 2
# вариант 3 передаем в метод лямбду преобразованную в блок
def bloc_method3
yield "test hello"
end
l = -> (msg) {puts msg}
bloc_method3 &l
# вариант 3
# вариант 4 передаем в метод блок, лямбду и процедуру
def bloc_method(my_proc3,my_lambda3)
yield "hello test"
my_proc3.call("hello cat")
my_lambda3.call("hello dog")
end
my_proc3= proc {|msg| puts msg }
my_lambda3 = lambda {|msg| puts msg }
bloc_method(my_proc3,my_lambda3) do |msg|
puts msg
end