Macros in Ruby?

Just wondering if there is a way to use macros in Ruby that does inline substitution, how does C work?

For instance:

define ARGS 1,2 sum(ARGS) # returns 3 

EDIT: More specifically, my problem is more like:

 @button1 = FXButton.new(self, "Button 1",:opts => BUTTONPROPERTIES,:width => width, :height => height) @button2 = FXButton.new(self, "Button 2",:opts => BUTTONPROPERTIES,:width => width, :height => height) @button3 = FXButton.new(self, "Button 3",:opts => BUTTONPROPERTIES,:width => width, :height => height) 

And ideally, I want the code to look like this:

 @button1 = FXButton.new(self, "Button 1", ALLBUTTONPROPERTIES) @button2 = FXButton.new(self, "Button 2", ALLBUTTONPROPERTIES) @button3 = FXButton.new(self, "Button 3", ALLBUTTONPROPERTIES) 

Please note that I have the variables “width” and “height” that will not be properly passed to the initialization of the FXButton class if I just set them to some given value. Is there some kind of code replacement that will take care of this problem?

+6
source share
4 answers

You do not need a macro. Just define a variable or constant.

 A = [1, 2] A.inject(:+) # => 3 

After editing your question

You can do the following:

 ALLBUTTONPROPERTIES = ->{{opts: => BUTTONPROPERTIES, width: width, height: height}} 

and in the context where the BUTTONPROPERTIES , width , height constants and variables are assigned a specific value, do the following:

 @button1 = FXButton.new(self, "Button 1", ALLBUTTONPROPERTIES.call) @button2 = FXButton.new(self, "Button 2", ALLBUTTONPROPERTIES.call) @button3 = FXButton.new(self, "Button 3", ALLBUTTONPROPERTIES.call) 
+9
source

There is no preprocess in ruby; macros do not make sense. Just use the string constant or any other type of constant you need.

+7
source

There is probably another way to do what you are trying to do. Preprocessor macros do not make sense, because Ruby is not a compiled language, it is an interpreted language.

In particular, for your example, there is a very clean way to do this:

 args = [1, 2] sum(*args) # equivalent to sum( 1, 2 ) 
+7
source

A solid way to solve your problem is likely to be slightly different from your approach:

 @buttons = ["Button 1", "Button 2", "Button 3"].map do |name| FXButton.new(self, name, :opts => BUTTONPROPERTIES, :width => width, :height => height) end 

In this example, you have no variables @button1 , @button2 , @button3 . Instead, @buttons is an array containing all three.

+3
source

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


All Articles