Newbie question

  • Thread starter Williams, Chris
  • Start date
W

Williams, Chris

------_=_NextPart_001_01C4D960.72CFE3F2
Content-Type: text/plain

Hi all,
I'm developing a rails web app here at work and I keep running into
a common thing in terms of setting instance variables with the property of a
form's parameter value. Basically I want the variable to take the
parameter's value if it exists, and to otherwise use a reasonable default.

I keep writing code like this:
if @params["limit"]
@limit = @params["limit"]
else
@limit = 50
end

if @params["chain"]
chain = @params["chain"]
else
chain = 1
end

Can someone please point me to a simpler, more succinct "ruby" way of doing
this?

Thanks,
Chris

------_=_NextPart_001_01C4D960.72CFE3F2--
 
F

Francis Hwang

@limit = @params["limit"] || 50

Hi all,
I'm developing a rails web app here at work and I keep running into
a common thing in terms of setting instance variables with the
property of a
form's parameter value. Basically I want the variable to take the
parameter's value if it exists, and to otherwise use a reasonable
default.

I keep writing code like this:
if @params["limit"]
@limit = @params["limit"]
else
@limit = 50
end

if @params["chain"]
chain = @params["chain"]
else
chain = 1
end

Can someone please point me to a simpler, more succinct "ruby" way of
doing
this?

Thanks,
Chris

Francis Hwang
http://fhwang.net/
 
F

Florian Gross

I keep writing code like this:
if @params["limit"]
@limit = @params["limit"]
else
@limit = 50
end

if @params["chain"]
chain = @params["chain"]
else
chain = 1
end

I'd do something like this

defaults = {
"limit" => 50,
"chain" => 1
# more defaults
}
@values = defaults.merge(@params)

And then do @values["limit"] instead of @limit. This however only makes
sense when there is a logical connection between those values. I'd
prefer it in that case because it is way less duplication.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
474,163
Messages
2,570,897
Members
47,434
Latest member
TobiasLoan

Latest Threads

Top