Compact if statement for Codegolf

D

Drew Olson

I'm working on my codegolfing skills and was wondering, what is the
shortest possible way to write the following in ruby:

if a==0
1
else
2
end

Thanks for the help!
 
K

khaines

I'm working on my codegolfing skills and was wondering, what is the
shortest possible way to write the following in ruby:

if a==0
1
else
2
end

a==0?1:2


Kirk Haines
 
J

James Edward Gray II

I'm working on my codegolfing skills and was wondering, what is the
shortest possible way to write the following in ruby:

if a==0
1
else
2
end

a==0?1:2

James Edward Gray II
 
D

dblack

Hi --

I'm working on my codegolfing skills and was wondering, what is the
shortest possible way to write the following in ruby:

if a==0
1
else
2
end

The smallest I can think of is:

a==0?1:2


David

--
David A. Black | (e-mail address removed)
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
 
A

ara.t.howard

Hi --



The smallest I can think of is:

a==0?1:2

if a will only have values 0 or 1 you could use

2**a

if a is always positive you could use

a>0?2:1

cheers.

-a
 
D

dblack

Hi --

if a will only have values 0 or 1 you could use

2**a

if a is always positive you could use

a>0?2:1

And if a is always 0 you could use:

1

Sorry, couldn't resist :)


David

--
David A. Black | (e-mail address removed)
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
 

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

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top