Return_on

Gavin S. wrote:

# do stuff

end
end

Or (saving an exception handler setup):

def reverse x
@cache[:x] ||= (
puts “CACHING”
x.reverse
)
end

@cache = {}

p reverse(“foo”)
p reverse(“foo”)

END

Output:

CACHING
“oof”
“oof”

Devin M. wrote:

Does begin…end really have some sort of overhead? I’ve found that one
the nicest looking yet, and I’d hate to dismiss it based on a false
perception.

The overhead is smaller than I remembered, pretty negligible apparently:

require ‘benchmark’

def meth_with_begin_end
x = begin 3 end
end

def meth_without_begin_end
x = 3
end

N = 10000000

Benchmark.bmbm do |b|
b.report(“meth_with_begin_end”) do
N.times {meth_with_begin_end}
end
b.report(“meth_without_begin_end”) do
N.times {meth_without_begin_end}
end
end

END

Rehearsal ----------------------------------------------------------
meth_with_begin_end 5.648000 0.000000 5.648000 ( 5.729000)
meth_without_begin_end 5.458000 0.000000 5.458000 ( 5.458000)
------------------------------------------------ total: 11.106000sec

                          user     system      total        real

meth_with_begin_end 5.708000 0.000000 5.708000 ( 5.718000)
meth_without_begin_end 5.608000 0.000000 5.608000 ( 5.608000)

William J. wrote:

@cache[:x] ||= begin
end
CACHING
end
“oof”
“oof”

Oof! Typo.

def reverse x
@cache[x] ||= (
puts “CACHING”
x.reverse
)
end

@cache = {}

p reverse(“foo”)
p reverse(“bar”)
p reverse(“foo”)
p reverse(“bar”)

END

Output:

CACHING
“oof”
CACHING
“rab”
“oof”
“rab”

Joel VanderWerf wrote:

Gavin S. wrote:

def x
@cache[:x] ||= begin
# do stuff
end
end

Or (saving an exception handler setup):

Does begin…end really have some sort of overhead? I’ve found that one
the nicest looking yet, and I’d hate to dismiss it based on a false
perception.

Devin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs