Jun 14, 2010

Use JavaScript-like "with" syntax in Ruby

JavaScript has "with" syntax. At first, I write a code without "with".


console.log(Math.cos(1/2)); //=> 0.8775825618903728
console.log(Math.sqrt(2)); //=> 1.4142135623730951



Then, I write with "with".


with(Math) {
console.log(cos(1/2)); //=> 0.8775825618903728
console.log(sqrt(2)); //=> 1.4142135623730951
}



On the other hand, Ruby has not "with" syntax.


puts Math.cos(1/2) #=> 1.0
puts Math.sqrt(2) #=> 1.4142135623731



Look! I can use "with" in Ruby!


with(Math) {
puts cos(1/2) #=> 1.0
puts sqrt(2) #=> 1.4142135623731
}



To do this, I wrote "with" function.


def with(obj, &block)
obj.instance_eval(&block)
end



So, I can use "with" syntax.


with(Math) {
puts cos(1/2) #=> 1.0
puts sqrt(2) #=> 1.4142135623731
}



Of course, other type of object is OK. String, Intger and so on.


with("I love Ruby.") {
puts reverse #=> .ybuR evol I
puts gsub(/Ruby/, "YUI") #=> I love YUI.
}



with(1) {
puts succ #=> 2
}

2 comments:

Anonymous said...

wew, YUI?^^

so good, hehe
santo

Anonymous said...

Any Idea why cos(1/2) delivers different results ?