How to Pass Arguments to Define_Method

How do you pass arguments to define_method?

The block that you pass to define_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So:

define_method(:say_hi) { |other| puts "Hi, " + other }

Define method parameters for meta programming in Ruby

Try passing an array or dictionary.

UPDATE:

if condition1
class_eval <<-EVAL
def #{"my_method"}(arg1)
end
EVAL
else
class_eval <<-EVAL
def #{"my_method"}
end
EVAL
end

UPDATE2:

if condition1
self.instance_eval <<-EVAL
def #{"my_method"}(arg1)
end
EVAL
else
self.instance_eval <<-EVAL
def #{"my_method"}
end
EVAL
end

UPDATE3:

# or
self.instance_eval("def method1(arg1) puts 'hellowa' + arg1.to_s; end")
self.instance_eval("def method2() puts 'hellowa2'; end")

# and then
method1(33) # => hellowa33
method2 # => hellowa2

define_method with predefined keyword arguments

You have to use eval to define arguments dynamically (not just keyword arguments), e.g. using class_eval:

class MyClass
name = :foo
args = [:bar, :baz]
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{name}(#{args.map { |a| "#{a}:" }.join(', ')}) # def foo(bar:, baz:)
[#{args.join(', ')}] # [bar, baz]
end # end
METHOD
end

MyClass.new.foo(bar: 1, baz: 2)
#=> [1, 2]

MyClass.instance_method(:foo).parameters
#=> [[:keyreq, :bar], [:keyreq, :baz]]

define_method: How to dynamically create methods with arguments

If I understand your question correctly, you want something like this:

class Product
class << self
[:name, :brand].each do |attribute|
define_method :"find_by_#{attribute}" do |value|
all.find {|prod| prod.public_send(attribute) == value }
end
end
end
end

(I'm assuming that the all method returns an Enumerable.)

The above is more-or-less equivalent to defining two class methods like this:

class Product
def self.find_by_name(value)
all.find {|prod| prod.name == value }
end

def self.find_by_brand(value)
all.find {|prod| prod.brand == value }
end
end

Ruby: Send define_method with block arguments

You have few issues, like using reserved words, not understanding the self (or rather not implementing your understanding correctly).

source.attribute_names.each do |attribute|
source.singleton_class.instance_eval do
define_method('next_by_' + attribute) do |object, user = nil|
if user
source.joins(:users)
.where("#{attribute} > ?", object.public_send(attribute))
.where(users: { id: user.id })
.first
else
source.where("#{attribute} > ?", object.public_send(attribute)).first
end
end
end
end

Is it possible to define method argument with default values in Java?

Java != PHP.

But you can write:

public void delete(String name){
delete(name, 0);
}

public void delete(String name, int user_id){/* ...*/}

How to define method with optional argument and argument unpacking?

You should use **kwargs for that.

def test_func(arg1, *args, **kwargs):
optional_arg = kwargs.get('optional_arg')
...

The only limitation is that the keyworded argument (optional_arg) must always be after keywordless arguments

>>> test_func("foo", optional_arg="bar", arg1, arg2, ...)
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>> test_func("foo", arg1, arg2, ..., optional_arg="bar")
...
>>> test_func("foo", arg1, arg2, ...)
...

Ruby pass arguments to block


...
#call block with argument and change context
def call_block(arg)
block = @@block
instance_exec(arg, &block)
end
end

s = SomeClass.new
s.call_block("test")

#<SomeClass:0x10308ad28>
"test"

Ruby define method to return proc which makes use of an argument

Your example has two problems:

  1. You can't call a "proc full of methods" like that -- it'll work as an association extension, but there the block is evaluated as a module body, not called.

  2. The def keyword resets the local variable scope. To get a value into a function, you can either define it using define_method instead (that block retains surrounding scope), or put the value somewhere else the function will be able to find it (a class variable, for example).


def test(word)
proc do
define_method(:hello) do
puts word
end
end
end

Class.new(&test("hello")).new.hello

Separately, if you're defining approximately the same method on several associations, there might be a simpler path by defining them as class-level scopes.

define method with parameters in objective C

In your example:

- (int)canFindSquare:(NSString *)param1 array:(NSArray *)param2{
NSLog(@"something");
}

All you need to do to use the params is call the names of the variables you setup. Your method is already declared to return an int, so you need to make sure that you return one when you are done. Then your caller can test for it. This should work

- (int)canFindSquare:(NSString *)param1 array:(NSArray *)param2{
NSLog(@"param1 is %@ and param2 is %@", param1, param2);

// Some tests
return 1;
}

Remember though that ObjC is very clear with how you call things. So you would call your method like this:

canFindSquare:aString array:anArray;

I'd take a look at Apple's Objective-C conventions guide to brush up on naming. For example I would call the second param "anArray" or something like that. This makes it much more clear what it is you are doing.



Related Topics



Leave a reply



Submit