Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macros in Ruby?

Tags:

ruby

macros

Just wondering, is there a way to use macros in Ruby that does an in-text substitution the way C would work?

For example:

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

EDIT: More specifically my problem looks 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'd want the code to look like:

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

Notice how I have "width" and "height" variables that won't properly be passed to the initialization of the FXButton class if I just set them to some predetermined value. Is there some kind of code substitution that would take care of this issue?

like image 929
thecooltodd Avatar asked Jun 14 '13 13:06

thecooltodd


1 Answers

You don't need a macro. Just define a variable or a constant.

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

After the edit to your question

You can do like this:

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

and within a context where the constants and variables BUTTONPROPERTIES, width, height are assigned some value, do this:

@button1 = FXButton.new(self, "Button 1", ALLBUTTONPROPERTIES.call)
@button2 = FXButton.new(self, "Button 2", ALLBUTTONPROPERTIES.call)
@button3 = FXButton.new(self, "Button 3", ALLBUTTONPROPERTIES.call)
like image 186
sawa Avatar answered Sep 28 '22 04:09

sawa