text:
Tips for golfing in Ruby
What general tips can you give for golfing in Ruby?
I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)
Please post one tip per answer.

Someone needs to write a language called Rub, which uses a single Unicode character for every Ruby token, kinda like Jelly and Pyth :)

The numbers 100 to 126 can be written as ?d to ?~ in 1.8.
On a similar note if you need a single-character string in 1.9 ?x is shorter than "x".
If you need to print a string without appending a newline, $><<"string" is shorter than print"string".
If you need to read multiple lines of input $<.map{|l|...} is shorter than while l=gets;...;end. Also you can use $<.read to read it all at once.
If you're supposed to read from a file, $< and gets will read from a file instead of stdin if the filename is in ARGV. So the golfiest way to reimplement cat would be: $><<$<.read.

?x yields the ascii code in general, so you can realistically get all the printables to digits in two characters. 1.9 is different, 'a'.ord yields the ascii number, but is four bytes longer than the decimal version.

You can use ?a.ord in 1.9, but that's still longer than the decimal.

An even golfier way to implement cat is to leave the ruby file completely empty (0 bytes) and insist that it should be run from the command line with the -p flag.

or, from @daniero's own answer, puts *$<

So in 1.8, all I have to do is go ?~ and it will return 126?

You can go beyond 126 using thinks like ☺ or ♫, or if you are crazy enough: ?﷽.ord=65021

@SimplyBeautifulArt Your username checks out so well for this one.

Use the splat operator to get the tail and head of an array:
head, *tail = [1,2,3]
head => 1
tail => [2,3]

This also works the other way:
*head, tail = [1,2,3]
head => [1,2]
tail => 3

Use the * method with a string on an array to join elements:
[1,2,3]*?,
=> "1,2,3"

Use abort to terminate the program and print a string to STDERR - shorter than puts followed by exit
If you read a line with gets, you can then use ~/$/ to find its length (this doesn't count a trailing newline if it exists)
Use [] to check if a string contains another: 'foo'['f'] #=> 'f'
Use tr instead of gsub for character-wise substitutions: '01011'.tr('01','AB') #=> 'ABABB'
If you need to remove trailing newlines, use chop instead of chomp

+1 for abort and ~/$/

Please explain how to use ~/$/

@MathieuCAROFF every time you call gets, its result is stored in the $_ variable.  /regex/ ~= string returns the index of the first match. Calling ~ on a regex is equivalent to /regex/ ~= $_. So it would be something like s=gets;l= ~/$/

End your end.
Try to remove end from your code.
Don't use def...end to define functions. Make a lambda with the new -> operator in Ruby 1.9. (The -> operator is a "stabby lambda", or "dash rocket".) This saves 5 characters per function.
# 28 characters
def c n
/(\d)\1/=~n.to_s
end

# 23 characters, saves 5
c=->n{/(\d)\1/=~n.to_s}

Method calls are c n or c(n). Lambda calls are c[n]. Changing each c n to c[n] costs 1 character, so if you can use c n more than 5 times, then keep the method.
All methods that take do...end blocks can take {...} blocks instead. This saves 3 to 5 characters. If the precedence of {...} is too high, then use parentheses to fix it.
# 48 characters
(?a..?m).zip (1..5).cycle do|a|puts a.join','end

# WRONG: passes block to cycle, not zip
(?a..?m).zip (1..5).cycle{|a|puts a.join','}

# 45 characters, saves 3
(?a..?m).zip((1..5).cycle){|a|puts a.join','}

Replace if...else...end with the ternary operator ?:. If a branch has two or more statements, wrap them in parentheses.
# 67 characters
if a<b
puts'statement 1'
puts'statement 2'else
puts'statement 3'end

# 62 characters, saves 5
a<b ?(puts'statement 1'
puts'statement 2'):(puts'statement 3')

You probably don't have while or until loops, but if you do, then write them in modifier form.
(a+=1
b-=1)while a<b

Are the parentheses around puts'statement 3' necessary?

Addition to w0lf

When working with arrays, .compact can be replaced with -[nil] to save 2 chars.

Combined with above -> you can make it even shorter with -[p] to save another 2 chars.

Use the short predefined variables wherever possible, e.g. $* instead of ARGV.  There's a good list of them here, along with a lot of other useful information.

Use operator methods instead of parentheses
Let's say you want to express a*(b+c). Because of precedence, a*b+c won't work (obviously). Ruby's cool way of having operators as methods comes to the rescue! You can use a.*b+c to make the precedence of * lower than that of +.
a*(b+c) # too long
a*b+c   # wrong
a.*b+c  # 1 byte saved!

This can also work with the ! and ~ operators (things like unary + or unary - don't work because their methods are -@ and +@, saving () but adding .@)
(~x).to_s # too long
~x.to_s   # error
x.~.to_s  # 1 byte saved!

Don't use the true and false keywords.
Use:

!p for true (thanks, histocrat!)
!0 for false. If all you need is a falsy value, then you can simply use p (which returns nil).

to save some chars.

Unless you actually need true (i.e. if a truthy value is enough, like in an if condition), you don't even need !!.

When you are using string interpolation, (as you should pr Martin Büttner's post), you don't need the curly brackets if your object has a sigil ($, @) in front of it. Useful for magical variables like $_, $&, $1 etc:
puts "this program has read #$. lines of input"

So also if you need to print a variable more than you use it otherwise, you may save some bytes.
a=42; puts "here is a: #{a}"; puts "here is a again: #{a}"
$b=43; puts "here is b: #$b"; puts "here is b again: #$b"

Isn't puts "here is b: "+b more shorter?

@vrintle In this particular example, yes. But for instance "here is b:#{b}, here is a:#{a}!!" is shorter than "here is b:"+b+", here is a:"+a+"!!". The linked post also provides more info

If you need to find if a particular element e is inside a range r, you can use
r===e

instead of the longer:
r.cover?(e) # only works if `r.exclude_end?` is false

or
r.member?(e)

or
r.include?(e)

Isn’t r===e even shorter?

@akuhn Yes, it is. Much Shorter. Thanks for pointing that out, it helped me shorten my code by 10 chars, which is huge: http://codegolf.stackexchange.com/a/6125/3527

You’re welcome. Everything that can be used in a switch statement has === implemented.

New features in Ruby 2.3 and 2.4
It's good to stay abreast of new language features that will help your golf game. There are a few great ones in the latest Rubies.
Ruby 2.3
The safe navigation operator: &.
When you call a method that might return nil but you want to chain additional method calls if it's not, you waste bytes handling the nil case:
arr = ["zero", "one", "two"]
x = arr[5].size
# => NoMethodError: undefined method `size' for nil:NilClass

x = arr[5].size rescue 0
# => 0

The "safe navigation operator" stops the chain of method calls if one returns nil and returns nil for the whole expression:
x = arr[5]&.size || 0
# => 0

Array#dig & Hash#dig
Deep access to nested elements, with a nice short name:
o = { foo: [{ bar: ["baz", "qux"] }] }
o.dig(:foo, 0, :bar, 1) # => "qux"

Returns nil if it hits a dead end:
o.dig(:foo, 99, :bar, 1) # => nil

Enumerable#grep_v
The inverse of Enumerable#grep—returns all elements that don't match the given argument (compared with ===). Like grep, if a block is given its result is returned instead.
(1..10).grep_v 2..5 # => [1, 6, 7, 8, 9, 10]
(1..10).grep_v(2..5){|v|v*2} # => [2, 12, 14, 16, 18, 20]

Hash#to_proc
Returns a Proc that yields the value for the given key, which can be pretty handy:
h = { N: 0, E: 1, S: 2, W: 3 }
%i[N N E S E S W].map(&h)
# => [0, 0, 1, 2, 1, 2, 3]

Ruby 2.4
Ruby 2.4 isn't out yet, but it will be soon and has some great little features. (When it's released I'll update this post with some links to the docs.) I learned about most of these in this great blog post.
Enumerable#sum
No more arr.reduce(:+). You can now just do arr.sum. It takes an optional initial value argument, which defaults to 0 for Numeric elements ([].sum == 0). For other types you'll need to provide an initial value. It also accepts a block that will be applied to each element before addition:
[[1, 10], [2, 20], [3, 30]].sum {|a,b| a + b }
# => 66

Integer#digits
This returns an array of a number's digits in least-to-greatest significance order:
123.digits # => [3, 2, 1]

Compared to, say, 123.to_s.chars.map(&:to_i).reverse, this is pretty nice.
As a bonus, it takes an optional radix argument:
a = 0x7b.digits(16) # => [11, 7]
a.map{|d|"%x"%d} # => ["b", "7"]

Comparable#clamp
Does what it says on the tin:
v = 15
v.clamp(10, 20) # => 15
v.clamp(0, 10) # => 10
v.clamp(20, 30) # => 20

Since it's in Comparable you can use it with any class that includes Comparable, e.g.:
?~.clamp(?A, ?Z) # => "Z"

String#unpack1
A 2-byte savings over .unpack(...)[0]:
"".unpack(?U)    # => [128123]
"".unpack(?U)[0] # => 128123
"".unpack1(?U)   # => 128123

Precision argument for Numeric#ceil, floor, and truncate
Math::E.ceil(1) # => 2.8
Math::E.floor(1) # => 2.7
(-Math::E).truncate(1) # => -2.7

Multiple assignment in conditionals
This raises an error in earlier versions of Ruby, but is allowed in 2.4.
(a,b=1,2) ? "yes" : "no" # => "yes"
(a,b=nil) ? "yes" : "no" # => "no"

Golf Math::E.ceil(1) to Math::E.ceil 1, and likewise for floor and truncate.

@SimplyBeautifulArt I expect that someone golfing in Ruby will be able to make that leap themselves.

For Enumerable#sum, .flatten.sum is 2 bytes shorter than .sum{|a,b|a+b}

(-Math::E).truncate(1) is equivalent to -Math::E.truncate(1) which is 1 byte shorter

&. can be used with subscripting like this a&.[]i (1 byte shorter than a&.at i). Although, if brackets are required, a||a[i] is 1 byte is shorter than a&.[](i) or a&.at(i)

$_ is last read line.

print - if no argument given print content of $_
~/regexp/ - short for $_=~/regexp/

In Ruby 1.8, you have four methods in Kernel that operate on $_:

chop
chomp
sub
gsub

In Ruby 1.9, these four methods exist only if your script uses -n or -p.
If you want to print some variable often then use trace_var(:var_name){|a|p a}

These are only available when you run Ruby with the -p or -n option.  Reference.

It seems that trace_var only works with global $variables

Another trick that works with -n or -p is using a regexp literal as a boolean: the regexp is implicitly matched against $_. See this answer of mine for an example.

Unlike the String methods with the same names, the listed Kernel methods modify $_ in place. Generally this behaviour is what is wanted, but worth noting the difference.

Build arrays using a=i,*a to get them in reverse order. You don't even need to initialize a, and if you do it doesn't have to be an array.

Use string interpolation!

To replace to_s. If you need parentheses around whatever you want to turn into a string, to_s is two bytes longer than string interpolation:
(n+10**i).to_s
"#{n+10**i}"

To replace concatenation. If you concatenate something surrounded by two other strings, interpolation can save you one byte:
"foo"+c+"bar"
"foo#{c}bar"

Also works if the middle thing is itself concatenated, if you just move the concatenation inside the interpolation (instead of using multiple interpolations):
"foo"+c+d+e+"bar"
"foo#{c+d+e}bar"

Avoid length in if a.length<n
length is 6 bytes, a bit costly in code golf. in many situations, you can instead check if the array has anything at a given point. if you grab past the last index you will get nil, a falsey value.
So you can Change:
if a.length<5 to if !a[4] for -5 bytes
or
if a.length>5 to if a[5] for -6 bytes
or
if a.length<n to if !a[n-1] for -3 bytes
or
if a.length>n to if a[n] for -6 bytes
Note: will only work with an array of all truthy values. having nil or false within the array may cause problems.

I always use size… But this is definitely better. BTW, works for String too.

New features in Ruby 2.7 (experimental)
Ruby 2.7 is in prerelease (as of 17 Jun 2019) and has some features that look great for golfing. Note that some of them might not make it into the final 2.7 release.
All changes in Ruby 2.7-preview1: https://github.com/ruby/ruby/blob/v2_7_0_preview1/NEWS
Numbered block parameters
This is my favorite. It lets you finally drop the |a,b| in a block:
Edit: The syntax was changed from @1 to _1.
%w[a b c].zip(1..) { puts _1 * _2 }
# => a
#    bb
#    ccc

Method reference operator: .:
Edit: This was unfortunately removed before release.
.: is syntactic sugar for the .method method, e.g.:
(1..5).map(&1r.:/)
# => [(1/1), (1/2), (1/3), (1/4), (1/5)]

Pattern matching
I'm not sure how much use this will see in golf, but it's a great feature for which I only have a contrived example:
def div(*a)
  case a
    in [0, 0] then nil
    in [x, 0] if x > 0 then Float::INFINITY
    in [x, 0] then -Float::INFINITY
    in [x, y] then x.fdiv(y)
  end
end

div(-3, 0) # => -Infinity

The pattern matching syntax has lots of features. For a complete list, check out this presentation: https://speakerdeck.com/k_tsj/pattern-matching-new-feature-in-ruby-2-dot-7
This is also the feature most likely to change before 2.7 is finished; it even prints a warning when you try to use it, which you should heed:

warning: Pattern matching is experimental, and the behavior may change in future versions of Ruby!

Beginless Range: ..3
Analogous to the endless Range introduced in 2.6, it may or may not have much use in golfing:
%w[a v o c a d o].grep(..?m)
# => ["a", "c", "a", "d"]

Enumerable#tally to count like elements
This could be useful in golfing:
%w[a v o c a d o].tally
# => {"a"=>2, "v"=>1, "o"=>2, "c"=>1, "d"=>1}

Enumerable#filter_map to filter+map in one
(1..20).filter_map {|i| 10 * i if i.even? }
# => [20, 40, 60, 80, 100]

If the block returns nil or false the element will be omitted from the result.
Integer#[] takes a second argument or range:
You've long been able to get a specific bit from an integer with with subscript notation:
n = 77 # (binary 01001101)
n[3] # => 1

Now you can get the value of a range of bits by a second length argument or a range.
n = 0b01001101
n[2, 4] # => 3 (0011)
n[2..5] # => 3

Note that bits are indexed from least- to most-significant (right to left).

The range in the Enumerable#filter_map example should be (1..10), I think?

The method reference operator didn't make it in, as I sadly discovered just now trying to use it to do a restricted source challenge.

@1 and @2 are apparently now _1 and _2.

Unfortunatelly .: didn't make it through preview and was reverted in 2.7 release https://bugs.ruby-lang.org/issues/16275

If you ever need to get a number from ARGV, get, or something similar to do something that many times, instead of calling to_i on it, you can just use ?1.upto x{do something x times} where x is a string.
So using ?1.upto(a){} instead of x.to_i.times{} will save you 2 characters.
You can also re-write things like p 1 while 1 or p 1 if 1 as p 1while 1 or p 1if 1
That example isn't very useful, but it could be used for other things.
Also, if you need to assign the first element of an array to a variable, a,=c will save two characters as opposed to a=c[0]

Don't use #each. You can loop over all elements just fine with #map. So instead of
ARGV.each{|x|puts x}

you can do the same in less bytes.
ARGV.map{|x|puts x}

Of course, in this case puts $* would be even shorter.

There are literals for rational and complex numbers:
puts 3/11r == Rational(3,11)
puts 3.3r == Rational(66,20)
puts 1-1.i == Complex(1,-1)

=> true
true
true

You can use most bytes within strings. "\x01" (6 bytes) can be shortened to "" (3 bytes). If you only need this one byte, this can be shortened even further to ? (2 bytes).
By the same token, you can get newlines shorter like this:
(0..10).to_a.join'
'

 => "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10"

You can use ?\n and ?\t as well, which is one byte shorter than "\n" and "\t". For obfuscation, there also ?\s, a space.

Use constants instead of passing arguments around, even if you need to change them. The interpreter will give warnings to stderr, but who cares. If you need to define more variables related to each other, you can chain them like this:
A=C+B=7+C=9

=> A=17, B=16, C=9

This is shorter than C=9;B=16;A=17 or C=0;B=C+7;A=C+B.

If you need an infinite loop, use loop{...}. Loops of unknown length may be shorter with other loops:
loop{break if'
'==f(gets)}

while'
'!=f(gets);end

Some more gsub/regexp tricks. Use the special '\1' escape characters instead of a block:
"golf=great short=awesome".gsub(/(\w+)=(\w+)/,'(\1~>\2)')

"golf=great short=awesome".gsub(/(\w+)=(\w+)/){"(#{$1}~>#{$2})")

And the special variables $1 etc. if you need to perform operations. Keep in mind they are defined not only inside the block:
"A code-golf challenge." =~ /(\w+)-(\w+)/
p [$1,$2,$`,$']

=> ["code", "golf", "A ", " challenge."]

Get rid of spaces, newlines, and parentheses. You can omit quite a bit in ruby. If in doubt, always try if it works without, and keep in mind this might break some editor syntax highlighting...
x+=1if$*<<A==????::??==??

"Please post one tip per answer." Also ?\n is nice, but not really shorter than actually putting a newline character inside quotes. (same for tab)

And puts$* is even shorter.

I know you were trying to prove a point but I'm pretty sure that last example is the same as x+=1;$*<<A

Save some bytes when removing repeated elements of an array
a.uniq # before
a|[]   # after
    ^^

If you will be using an empty array [] in a variable, you can save even more bytes:
a.uniq;b=[] # before
a|b=[]      # after
      ^^^^^

For the first case, a&a is 1 byte shorter

Scientific notation can often be used to shave off a char or two:
x=1000
#versus
x=1e3

Note: This will return a Float value (1000.0) instead of an Integer, which may cause inaccurate results with large numbers.

Ah, nice 1e2 is better than 100.0 when a percentage is needed.

Similar to this principle, 1.0* is 1 char shorter than .to_f

To my surprise, this trick works with Integer#upto and Integer#downto, e.g. 1.upto(1000) can become 1.upto(1e3). (Both forms iterate over integers.)

Kernel#p is a fun method.
Use p var instead of puts var. This works perfectly with integers and floats, but not with all types. It prints quotation marks around strings, which is probably not what you want.
Used with a single argument, p returns the argument after printing it.
Used with multiple arguments, p returns the arguments in an array.
Use p (with no arguments) instead of nil.

Unfortunately p 'some string' prints "some string" and not just some string which is often criticised by others.

Basically p s is the same as puts s.inspect, but it returns s

Yet another way to use the splat operator: if you want to assign a single array literal, a * on the left-hand side is shorter than brackets on the right-hand side:
a=[0]
*a=0

With multiple values you don't even need the splat operator (thanks to histocrat for correcting me on that):
a=[1,2]
a=1,2

The latter case doesn't actually need the splat.

@histocrat Oh wow, I thought the second value would just be discarded in that case.

I can't believe I haven't known these in all the time I've spent golfing in Ruby.

To join an array, instead of this
[...].join

do this
[...]*''

which saves 2 bytes.
To join with a separator use
[...]*?,

Save a byte when printing a word with symbols
This is a bit situational, but every byte counts!
puts"thing" # before
puts:thing  # after
          ^

Avoid Array#repeated_permutation and Array#repeated_combination
Credit to @AsoneTuhid who golfed the code for repeated permutations of length \$\ge5\$.
Some of Ruby's built-in methods have unfortunately long names. Never use Array#repeated_permutation or Array#repeated_combination; save bytes as follows.
Repeated permutations
Assume a is an array. To get repeated permutations of length \$L = n + 1\$ of the elements of a:
a.product(a,a,a)  # L <= 4; number of arguments = n
a.product(*[a]*n) # L >= 5

Depending on context, the parentheses may not be required. Both of the above yield an array. To iterate over the permutations, simply call with a block.
Repeated combinations
For repeated combinations of length \$L\$, use one of
a.send(a.methods[42],L)    # enumerator
[*a.send(a.methods[42],L)] # array

The index that yields :repeated_combination depends on the Ruby version and possibly the OS (42 is correct for Ruby 2.5.5 on Linux, which is the version on TIO at the time of writing). The default indexing may also be disrupted if any libraries are loaded. The correct index in any case can always be found using [].methods.index(:repeated_combination).

In general, calling a method by index using Object#send and Object#methods, as demonstrated above for repeated combinations, is shorter than a direct method call when the number of bytes in the method name and the index of the method in the methods array satisfy:

+-------+-------+
| Bytes | Index |
+-------+-------+
|  19+  |  0-9  |
|  20+  | 10-99 |
|  21+  | 100+  |
+-------+-------+
Subtract 1 from byte count if parentheses not needed for send.

17 bytes

@AsoneTuhid Very nice. Seems so obvious now that I see it. Thanks!

Use Goruby instead of Ruby, which is something like an abbreviated version of Ruby. You can install it with rvm via
rvm install goruby

Goruby allows you to write most of your code as you would be writing Ruby, but has additional abbreviations built in. To find out the shortest available abbreviation for something, you can use the helper method shortest_abbreviation, for example:
shortest_abbreviation :puts
#=> "pts"

Array.new.shortest_abbreviation :map
#=> "m"

String.new.shortest_abbreviation :capitalize
#=> "cp"

Array.new.shortest_abbreviation :join
#=> "j"

Also very handy is the alias say for puts which itself can be abbreviated with s. So instead of
puts [*?a..?z].map(&:capitalize).join

you can now write
s [*?a..?z].m(&:cp).j

to print the alphabet in capitals (which is not avery good example). This blog post explains more stuff and some of the inner workings if you are interested in further reading.
PS: don't miss out on the h method ;-)

More than 2 years later and I finally figured out what this answer reminds me of...

I just attempted a TDD code-golf challenge i.e. Write shortest code to make specs pass. The specs were something like
describe PigLatin do
  describe '.translate' do
    it 'translates "cat" to "atcay"' do
      expect(PigLatin.translate('cat')).to eq('atcay')
    end
    # And similar examples for .translate
  end
end

For the sake of code-golf, one need not create a module or class.
Instead of
module PigLatin def self.translate s;'some code'end;end

one can do
def(PigLatin=p).translate s;'some code'end

Saves 13 characters!

Ha, very thorough. Not only did you add the necessary behavior to PigLatin, but also to @pig_latin, $pig_latin, and 'pig'['latin'].

@histocrat: Now I get it. It's because translate has been defined on nil.

When a challenge requires that you output multiple lines, you don't have to loop through your results in order to print each line of e.g. an array. The puts method will flatten an array and print each element on a separate line.
> a = %w(testing one two three)
> puts a
testing
one
two
three

Combining the splat operator with #p you can make it even shorter:
p *a

The splat operator (technically the *@ method, I think) also casts your non-array enumerables to arrays:
> p a.lazy.map{|x|x*2}
#<Enumerator::Lazy: #<Enumerator::Lazy: [1, 2, 3]>:map>

vs
> p *a.lazy.map{|x|x*2}
2
4
6

*@ is not a method, splat is syntactic sugar

Subscripting Numbers!
I just discovered this yesterday. n[i] returns n's bit at the i-th position.

Example:
irb(main):001:0> n = 0b11010010
=> 210
irb(main):002:0> n[0]
=> 0
irb(main):003:0> n[1]
=> 1
irb(main):004:0> n[2]
=> 0
irb(main):005:0> n[3]
=> 0
irb(main):006:0> n[4]
=> 1
irb(main):007:0> n[5]
=> 0

And now you can use more arguments such as n[0..3]

On looping
while...end
If you need to break out of the loop, while condition;code;end will probably be shorter than loop{code;condition||break}.
The ; before end is not always required, eg. while condition;p("text")end
until c;...;end is equivalent to while !c;...;end and 1 byte shorter.
Note that in most cases code while condition and code until condition are significantly shorter as they don't require the end keyword and can often drop semicolons. Also, i+=1 while true is equivalent to i+=1while true and 1 byte shorter.
redo
When run, the redo command jumps back to the beginning of the block it's in.
When using redo in a lambda, you will have to move any setup variables to the arguments to avoid them being reset at every iteration (see examples).
recursion
Recursion can be shorter is some cases. For instance, if you're working on an array element by element, something like f=->s,*t{p s;t[0]&&f[*t]} can be shorter than the alternatives depending on the stuff.
Note that per the current consensus, if you're calling your function by name, you need to include the assignment (f=) in the byte count making all recursive lambdas 2 bytes longer by default.
eval
If you need to run some code n times, you can use eval"code;"*n.
This will concatenate code; n times and run the whole thing.
Note that in most cases you need to include a ; after your code.
Examples
A lambda to print all numbers from 1 to a inclusive:
->n{i=0;loop{p i+=1;i<n||break}} # 32 bytes
f=->n,i=1{i>n||p(i)&&f[n,i+1]}   # 30 bytes
->n,i=0{p(i+=1)<n&&redo}         # 24 bytes
->n{i=0;p i+=1while i<n}         # 24 bytes
->n{i=0;eval"p i+=1;"*n}         # 24 bytes
->n{n.times{|i|p i+1}}           # 22 bytes # thanks to @benj2240
->n{n.times{p _1+1}}             # 20 bytes # thanks to @AgentIvan

In this case, since the end-point is defined (n), the n.times loop is the shortest.
The redo loop works because i+=1 modifies i and returns its new value and p(x) returns x (this is not true of print and puts).
Given a function g and a number n, find the first number strictly larger than n for which g[n] is truthy
->g,n{loop{g[n+=1]&&break};n}     # 29 bytes
f=->g,n{g[n+=1]?n:f[g,n]}         # 25 bytes
->g,n{1until g[n+=1];n}           # 23 bytes
->g,n{(n+1..).find &g}            # 22 bytes
->g,n{g[n+=1]?n:redo}             # 21 bytes

In this case, with an unknown end-point, redo is the best option.
The (n+1..Inf) loop is equivalent to simply looping indefinitely but more verbose.
A 1 (or anything else) is required before the until keyword to complete the syntax, using a number allows you to drop a space.
The eval method is not viable in this case because there is neither a defined end-point nor an upper bound.
Update: with the new open ranges (n+1..Inf) can be written simply as (n+1..), also .find{|x|g[x]} is equivalent to .find &g where g is converted to a block.

TL;DR check out redo, it can very often shave off a couple of bytes

.times can often be even shorter for fixed loops, eg ->n{n.times{|i|p i+1}} for 22 bytes

Use || instead or and && instead and.
Beside the one character from and you can save the spaces
(and perhaps the bracket) around the operator.
p true and false ? 'yes' :'no'   #-> true (wrong result)
p (true and false) ? 'yes' :'no' #-> 'no'
p true&&false ? 'yes' :'no'      #-> 'no', saved 5 characters

p true or false ? 'yes' :'no'   #-> true (wrong result)
p (true or false) ? 'yes' :'no' #-> 'yes'
p true||false ? 'yes' :'no'      #-> 'yes', saved 4 characters

If you loop on an array you normally use each. But map loops also over an array and it is one character shorter.

If the first line starts with #! and contains ruby, then Ruby will take command-line switches from it.
For example, if you require two libraries, you can golf
require'benchmark'
require'prime'

into
#!ruby -rbenchmark -rprime

which saves 7 bytes.

Or you can just add -rbenchmark -rprime to the character/byte count. That's usual in choice golf.

You may be able to save 2 chars and use
[*(...)]

instead of
(...).to_a

For example, suppose we have a range that we want as an array:
(1..2000).to_a

Just do it like this:
[*1..2000]  #  Parentheses around the (ran..ge) is not needed!

And now you have your range as an array.

I think [*1..2000] works, too?

Re(ab)use predefined globals
There is a whole bunch of predefined global variables that you can use instead of initialising new variables.
A very common example is that you have some golfed one-liner that loops, but you also need to keep a counter for later:
i=0
s.gsub!(/../){i+=1;"foo"}while s=~/.../
p i

So frustrating. Luckily, $. comes to the rescue! It is initially 0, and is incremented each time you read a line from input. This is of course incredibly useful if you actually need to keep track of the amount of lines you have read, but otherwise you can just manually update it:
s.gsub!(/../){$.+=1;"foo"}while s=~/.../
p$.

That's 3 bytes saved.
If you for example need to append your counter to a string s, you may save some more bytes though string interpolation because the variable has a sigil:
i=0;i+=1;s+i.to_s
i=0;i+=1;s+"#{i}"
$.+=1;s+"#$."

Another interesting global is $:. It's an alias for $LOAD_PATH and is an array full of strings. I haven't actually used this in a golf yet, but I imagine it could come in handy if you need a cache for checking previously visited values or something, and don't care if it's completely empty. Your values are unlikely to crash with any of its initial contents anyways.

Especially for new golfers, it's worth noting that you generally can't use $. as a counter like this in function submissions because of this consensus regarding function reuse. (I was guilty of doing so a couple of times before I became aware of that rule.)

<< trick
a.push x

can be shortened to:
a<<x

for -4 bytes.

Note: this also works for Strings

To subtract one (-1), instead of doing this
(i - 1) * 2

do the following
~-i * 2

which will save you 2 bytes in cases where you otherwise have to use brackets (e.g. arithmetics).

like wise, (i+1) can become -~i

Array#assoc/rassoc
When you have an array of arrays and want to find the sub-array that starts with a particular value, don't use Enumerable#find, use Array#assoc:
a = [[0,"foo"],[0,"bar"],[1,"baz"],[0,"qux"]]
a.find{|x,|x==1} # => [1,"baz"]
a.assoc(1) # => [1,"baz"]

This is also a good replacement for Enumerable#any? in some situations.
Array#rassoc does the same thing, but checks the sub-arrays' last element:
a = [[123,"good"],[456,"good"]]
a.any?{|*,x|x=="bad"} # => false
a.rassoc("bad") # => nil

For the a.any? line in the rassoc  example, what does |x,| do? How is it different from |x|?

@Cyoce Block parameter destructuring follows the same rules as destructuring assignment, so it's like x=[1,2] vs x,=[1,2]. Using my example above, with |x|, in the first iteration x will be [0,"foo"]. With |x,y|, x will be 0 and y will be "foo". Likewise, with |x,|, x will be 0. In other words, it says "put the first element in x and throw the rest away.

Note that it doesn't work in reverse, e.g. |,y| is a SyntaxError, ergo |_,y|. But I've just now realized that |*,y| works, which is cleaner than using a variable named _ (but no shorter).

Fun with arrays
There are many ways to do the same thing in ruby, and often times the default methods are inefficient - as a case study, a new arrays with set size and initialized to all 10:
Array.new(20,10) # idiomatic
[10]*20

You may already be informed not to use this syntax, however, when you are initializing elements in an array that needs to not be shallow-cloned, for example 2D arrays:
[[]]*20               # beware, all 20 elements points to the one same array
Array.new(20){[]}     # idiomatic
20.times.map{[]}
([0]*20).map{[]}      # free ticket, you can move any line into `0` to save newline
([a,b,c,d]*5).map{[]} # saves a char when you move 4 1-time use expressions
(1..20).map{[]}

Many operations in ruby will create new objects. Sometimes this is to our advantage. For example, to create a new array with the same size as another array, we can get by without even knowing its .size at all:
[0]*a.size # looks kinda nice
a.map{0}   # -2 chars

(Note: the []* version may be preferable in cases where you also want to reuse the value, so [0]*b=a.size might end up helping you cut a char elsewhere)
To shallow clone an array:
b=a[0..-1] # makes sense
b=a.clone
b=a*1      # this returns new_ary
b=*a       # this version for assignments - use [*a] in expressions

.clone is an alias of .dup ([*a] is still better for arrays)

Use eval instead of reduce
While array.sum is great and shorter than array.reduce(:+), there are no similar methods for the other operators *, -, / ...
Joining arrays and evaling them saves some space:
a = [1,2,3,4]

a.reduce(:*)   # => 24
eval(a*?*)     # => 24
          ^^   two bytes saved.

It also removes the need to map string input to numbers first:
b = "1 2 3 4".split

b.map(&:to_i).reduce(:*)
eval(b*?*)
          ^^^^^^^^^^^^^^

eval a*?* to save another char.

also for case 2, using .tr' ',?* is way more concise than .split*?*...

also, note that a.reduce:* is valid if brackets aren't required though I think it can always be replaced with eval a*?*

eval(a*?*) is horrible. I like it!

New features in Ruby 2.5 and 2.6
Ruby keeps getting new features that look like they could be handy for golfing. Here are some that caught my eye. If there's any you think should be added feel free to edit or mention them in the comments.
(See also New features in Ruby 2.3 and 2.4.)
Ruby 2.5
Here's an easy-to-read reference with all of the new features in Ruby 2.5: https://rubyreferences.github.io/rubychanges/2.5.html
Regexp absence operator: (?~foo)
This matches any string that doesn't end with foo. I don't have a specific use for this one off the top of my head, but here's a good article about it.
Enumerable#all?, any?, none?, and one? accept objects that respond to ===
Similar to Enumerable#grep:
%w[Foo bar].one?(/[A-Z]/) # => true
%w[Foo bar].any?("bar") # => true
[1, 2, 3, 5, 7, 11].all?(0..10) # => false

Hash#slice gets a subset of a Hash
I don't see a lot of Hashes in Ruby golf, but it might come in handy:
{foo: 1, bar: 2, baz: 3}.slice(:bar, :baz) # => {foo: 1, bar: 2}

Ruby 2.6
All of the changes in Ruby 2.6: https://rubyreferences.github.io/rubychanges/2.6.html
Endless Range: 1..
Lots of potential uses for this.
%w[a b c].zip("X"..).to_a
# => [["a", "X"], ["b", "Y"], ["c", "Z"]]

[1, 2, 3, 5, 7, 11].any?(10..)
# => true

String#split takes a block
Saves four bytes when iterating over the result of String#split, e.g.:
"foo;bar;baz".split(?;).map {|s| x << s.upcase if ... }

You can do this:
"foo;bar;baz".split(?;) {|s| x << s.upcase if ... }

Note that it still returns the original string, so it won't always be fewer bytes than map.
Proc composition with >> and <<
Procs now have >> and << methods that let them be combined with other procs, or any object that responds to call:
double = ->n{ n * 2 }
square = ->n{ n ** 2 }
(double >> square)[5] # => 100
(double << square)[5] # => 50

% operator for Range
An alias for Range#step:
((1..10) % 2).to_a
# => [1, 3, 5, 7, 9]

Random.bytes
Could be handy.
Random.bytes(10)
# => "'\xB2\xD7\ny"

Avoid String#sub!
Instead of
a.sub!b,c

save a byte with
a[b]&&=c

Both return nil if no substitution occurs. If a substitution does occur, be aware that the return values differ: a.sub!b,c returns the modified string a whereas a[b]&&=c returns c. However, given that you're using sub! (as opposed to sub) chances are that either:

You just need to modify a in place and will be discarding the return value anyway; or
You just need the return value to be truthy.

The shorter form meets your needs in both cases.

When working with arrays, .compact can be replaced with -[nil] to save 2 chars.

-[p] saves another 2.

When getting input of fixed length the optional integer parameter to gets may come in handy.

Getting a substring:
gets 10 vs gets[0,10] -- saves 3 bytes
Cutting trailing newline:
gets 10 vs gets.chop -- saves 3 - log10(required_length)  bytes (= 2 in this case)

Cloning strings
Strings are mutable in Ruby so if you have two variables holding the same string (a=b="string") and you modify one (a[0]="S"), the other will also change (b=="String")
To clone a string:
a="string"

b=a.clone # 9 bytes
b=a.dup # 7 bytes
b=+-a # 5 bytes
b=-a # 4 bytes (b will be frozen)

b=a*1 is yet another way.

Use ~// and !// to match against $_ (last line read)
These can be used with the -n or -p flags.
~/regex/ is equivalent to $_=~/regex/ returning the index of the first match or nil.
Try it online!
!/regex/ equivalent to $_!~/regex/ returning true or false.
Try it online!
Note that !// is weird as it doesn't call the ! method on the regex but only if you use a literal.
!/regex/ matches the expression.
r=/regex/;!r calls the ! (not) method and always returns false.
Also, !r=/regex/ gives an assignment in conditional warning so there's some syntactic sugar going on.

Filtering a specific class from an Array
Suppose, you've to choose only Integer from
a = [1, 2, "3", 4.0, [5], "6".to_sym, 7r]

then you can do,
a.keep_if{|x|x.kind_of? Integer} # 32 bytes
a.keep_if{|x|x.is_a? Integer} # 29 bytes
a.select{|x|x.is_a? Integer} # 28 bytes
a.select{|x|Integer===x} # 24 bytes
a.grep(Integer) # 15 bytes

Try it online!

You can use Numeric class in case you want numbers only.

To generate symmetric output, you can use a single range like (-x..x) and then map a function on the absolute value:
(-8..8).map{|x|x.abs}
Use short-circuit evaluation of boolean expressions to avoid if...else: x>1&&s+=x
To check if an integer array a contains a number x, you can use a-[x]!=a, especially useful if  x is an expression.
Defining a variable as an accumulator is often shorter than using map and then reduce.
Use string interpolation with % for alignment: "x%12s"%?x is shorter than ?x+11*" "+?x or for base conversions: "%b"%65 vs 65.to_s(2)
Use complex number for trigonometric functions: -1.argis PI, 1i.arg is PI/2, (a+b*1i).arg is Math.atan(b/a) and works even when a and b are integers.

If all you need is the absolute value (no other manipulation), (-8..8).map &:abs saves four characters (three if you need to surround the argument in parentheses for additional method chaining afterwards).

Is it an array?
Originally from histocrat.
Rather than writing
a.class==Array  # 14 bytes

you could write
a.is_a? Array   # 13 bytes

or even
a!=[*a]         # 7 bytes

Alternative a*0==[]

String split function uses $; or space by default; if input is space-seperated, you can omit the argument.
# Reads 3 integers from line 1 of input file
x,y,z=gets.split.map &:to_i

Or, you can configure the behaviour of ARGF with $/ (if there is only one line):
# Reads 3 integers from input file
# Not seperated by newlines, so in case of:
# 1 2
# 3 4
# You will get: 1 2 4 ("2\n3".to_i -> 2)
$/=' '
x,y,z=$<.map &:to_i

Due to the predictable behaviour of .to_i / .to_f, if you only have two numbers, you can use string.to_i(/.to_f) to get the first number and substring after the non-digit (even simpler for space) for the two values. There are tricks if you already know the constraints on the length of the numbers and especially so if the first one is length 1-2:
v=gets           # 1 2 / 11 22 / 11 22222222222222222222 / 123 4567890123456
v.to_i           # 1*    11*     11*                       123*
v[2,9].to_i      # 2*#$  22*#$   22222222                  3
v[2,99].to_i     # 2#$   22#$    22222222222222222222*#    3
v[2..-1].to_i    # 2#    22#     22222222222222222222*#    3
v[/\d+$/].to_i   # 2     22      22222222222222222222      4567890123456
v[~/ /,9].to_i   # 2$    22$     22222222                  45678901
v[~/ /,99].to_i  # 2     22      22222222                  4567890123456*
v[~/ /..-1].to_i # 2     22      22222222                  4567890123456
*: recommend to use in cases as specific than this
#: 1st int in string length is expected to be <=2 (-10 < x < 100)
$: 2nd int in string length is expected to be <=8 (if 1st int is length 1: <=9)
Note: [x,99] will take 99 characters, while ..-1 goes all the way to end of string. Because ~/ / matches the index of the space, this should be accounted for: [~/ /,9] will get length 8 int at most, as first char is the space
Note: If there are three+ numbers, please just use split or map
The above trick can be combined with $_:
p *gets.to_i..$_[2,9].to_i

Handy ways to repeat strings:
# aaaaabcbcbcbcaaaaa,aaaaa,aaaaa
$><<?a*5+'bc'*4+[?a*5]*3*?,

Shorthand for size of input line:
p (eval gets.chars*?+)/~/$/
# is equivalent to:
p (eval gets.chars*?+)/$_.size

To check if a is an Array, instead of doing:
a.kind_of?(Array)

you can do
a.to_s['[']

Won't work if a can be a string that contains [.

Or use the triple equals thing: Array===a ;)

How about a==[*a]?

Default function arguments
Pre-defining your variables within a function can save you from calling particular arguments if you already know what they are and are calling the function multiple times.
def f(a,b,c)
  return a+b+c
end
puts f(f(3,3,3),f(3,3,3),f(3,3,3))
# => 27

One can shorten this quite easily:
def f(a,b=3,c=3)
  return a+b+c
end
puts f(f(3),f(3),f(3))
# => 27

If you do not assign any second or third arguments, then b=3 and c=3 automatically.  One can shorten this further:
def f(a,b=a,c=a)
  return a+b+c
end
puts f(f(3))
# => 27

Note however that you'll need to give it at least one variable, the first one, and I'm not quite sure how you can avoid assigning a value to b while assigning a value to c.

See here for more argument methods.

The <=> (spaceship) operator compares two expressions and returns -1, 0, or 1. Applies to anything that can be compared with <, >, and ==.
Some example uses:
x<=>0 is equivalent to the sign function.
x.*x<=>0 is the absolute value of x.

Quick way to check if all items in a Ruby array are unique lists various ways to check whether everything in an array is unique. Unfortunately, none of them are methods that I can send to a receiver, I need to have my array on both sides of an operator. Lame!
Fortunately, uniq! returns nil if no changes are made, and returns the modified array if changes are made, meaning that it can be placed at the end of a pipeline to check for uniqueness;
x.method1.method2.method3.uniq! ? "not unique" : "everything is unique!"
Various other shouty methods have similar behaviour - returning the modified array if changes are made and nil if no changes are made.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
IPv4 Integer Conversion Function
Write the shortest function to convert an IP address into it's integer representation and output it as an integer.
To change an IPv4 address to it's integer representation, the following calculation is required:

Break the IP address into it's four octets.
(Octet1 * 16777216) + (Octet2 * 65536) + (Octet3 * 256) + (Octet4)

Sample Input
192.168.1.1           10.10.104.36           8.8.8.8

Sample Output
3232235777            168454180              134744072

I think this would be better if there was a restriction in place prohibiting a language's built-in functions.

@George - Yea, it would have been, but people had already done it before the I could put that in - I honestly didn't think about it.

PHP - 21 Characters
<?=ip2long($argv[1]);

MySQL - 20 Characters
SELECT INET_ATON(s);

C: 79 characters
main(i,a)char**a;{i=i<<8|strtol(a[1],a+1,0);*a[1]++?main(i,a):printf("%u",i);}

EDIT: removed C++, would not compile without headers; with GCC, the printf and strtol function calls trigger built-in functions, hence headers can be skipped. Thx to @ugoren for the tips. This will compile as is without additional options to gcc.
EDIT2: return is actually redundant :)

very clever use of main() :) .. my version was 116bytes.

I get a segmentation fault.

@George, what is your input and how are you running it?

I'm running it with my UserScript through http://codepad.org

This won't work in C++, you can't call main recursively.

Very nice. Can save a few characters though: K&R style saves 6 with main(i,a)char**a;{..., and &a[1] is a+1.

@Bunnit, it will (may not be standards compliant), however the only difference is that printf and strtol are not built-in functions, so need to include two headers explicitly! I'll remove the c++ from the answer...

@ugoren, thx for the tips!

@Nim, it is illegal to call main() in C++, it is one of the differences between C and C++.  It's explicitly stated in the standard.  It might compile but it's UB.

Actually the question only asks for a function anyway so it doesn't even have to be main.  So you could save an extra six characters by using a single letter name.(Also now it should definitely not compile on any C++ compiler due to the default ints)

Ruby (no builtins/eval) - 47
s=->s{s.split(".").inject(0){|a,b|a<<8|b.to_i}}

Test:
s["192.168.1.1"]
3232235777

Befunge - 2x11 = 22 characters
So close, Befunge will win one day.
>&+~1+#v_.@
^*4*8*8<

Explanation
The biggest distinguishing feature of Befunge is that instead of being a linear set of instructions like most languages; it is a 2d grid of single character instructions, where control can flow in any direction.
>      v
^      <

These characters change the direction of control when they are hit, this makes the main loop.
 &+~1+

This inputs a number and pushes it onto the stack (&), pops the top two values off the stack, adds them and pushes them back onto the stack (+), inputs a single character and places its ascii value on the stack (~), then pushes 1 onto the stack and adds them (1+).
The interpreter I've been using returns -1 for end of input, some return 0 instead so the 1+ part could be removed for them.
      #v_.@

The # causes the next character to be skipped, then the _ pops a value off the stack and if it is zero sends control right, otherwise sends it left.  If the value was zero . pops a value off the stack and outputs it as an integer and @ stops the program.  Otherwise v sends control down to the return loop.
^*4*8*8<

This simply multiplies the top value of the stack by 256 and returns control to the start.

Pardon my ignorance, but should that be 19 chars? I understand why you say 2x11, but why does it work that way?

Befunge is a 2d language, if you look for the >v<^ that is actually the main loop in this program.  I guess in this case control doesn't actually pass through those last 3 spaces on the bottom, but I find it easiest to just count Befunge programs as the smallest bounding rectangle; and if you were to try and count control flow you get into trouble with self-modifying programs.

Golfscript -- 16 chars
{[~]2%256base}:f

As a standalone program, this is even shorter at 11.
~]2%256base

Extremely straightforward. Evaluates the input string (~) and puts it into an array []. Since the .s in the string duplicate the top of the stack, we only take every other term in the array (2%). We now have an array which basically represents a base 256 number, so we use a built-in function to do the conversion. (256base).

very clever. i guess base256 is treated differently to say base10 or base16 then where 48=>0?

@gnibbler: I'm not sure what you're suggesting -- the base function handles all bases the same way, e.g. {:B;{\B*+}*}:base (although the real function is overloaded for conversions the other way). Interesting to note is that base conversion for strings is the same as arrays (as strings are just arrays without nesting, but with a different output format).

yeah i was thinking of base conversions of strings, so i didn't look closely enough at base for my answer

Very clever. Now do that for an IPv6 address. :)

Ruby (40)
q=->x{x.gsub(/(\d+)\.?/){'%02x'%$1}.hex}

->
q["192.168.1.1"]
=> 3232235777

Nice idea of using regexp.

Very clever!  Also you can write to_i 16 as hex to save some characters.

thanks @chron that made both this and link 4 characters shorter

Ruby - 46 chars
require"ipaddr"
def f s;IPAddr.new(s).to_i;end

I think that constitutes cheating. ;-)

Bash - 46
Table of content
You will find 4 differently golfed version:

echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]                        # 46chr
set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]                       # 47chr
v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]     # 65chr
mapfile -td. i<<<$1;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o  # 68chr

New version! 2018-11-15 More golfed, 46 char
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]

Explanation

I used $_ for more golfing.
Syntax ${1//./ }will substitute every dots . by spaces .
so printfwill render something like 192<<(_-=8)|168<<(_-=8)|1<<(_-=8)|1<<(_-=8)|
then we will add a 0 after last OR | and
preset _ to 32. bash will read construct from left to right, so $((_-=8)) make 24 at 1st shift, 16 on second, and so on.

in action:
set -- 192.168.1.1
echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]
3232235777

For fun: trying to get $_ content, after this:

echo $_
3232235777

;-b
set -- 192.168.1.1
echo $_ $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0] $_
192.168.1.1 3232235777 0

Ok, that's correct 32 - 4 x 8 = 0

In a function:
ip2int() {
    echo $[_=32,`printf "%d<<(_-=8)|" ${1//./ }`0]
}
ip2int 192.168.1.1
3232235777
ip2int 255.255.255.255
4294967295
ip2int 0.0.0.0
0

or into a loop: -> 60
ip2int() {
    for i;do
        echo $[_=32,`printf "%d<<(_-=8)|" ${i//./ }`0]
    done
}

ip2int 192.168.1.1 10.10.104.36 8.8.8.8 1.1.1.1 255.255.255.255 0.0.0.0
3232235777
168454180
134744072
16843009
4294967295
0

bash (v4.1+): 47
First post
set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]

Explanation:

Syntax ${1//./ }will substitute every dots . by spaces .
set -- set positional parameters ($@=($1 $2 $3...))
So set -- ${1//./ } will split $1 by dots and set $1, $2, $3 and $4 if string containg 3 dots (and no spaces).

in action:
set -- 192.168.1.1
set -- ${1//./ };echo $[$1<<24|$2<<16|$3<<8|$4]
3232235777

or in a function:
ip2int() {
    set -- ${1//./ }
    echo $[$1<<24|$2<<16|$3<<8|$4]
}
ip2int 192.168.1.1
3232235777
ip2int 0.0.0.0
0

or into a loop: -> 61
for i;do set -- ${i//./ };echo $[$1<<24|$2<<16|$3<<8|$4];done

in action:
ip2int() {
    for i;do
        set -- ${i//./ }
        echo $[$1<<24|$2<<16|$3<<8|$4]
    done
}

ip2int 192.168.1.1 10.10.104.36 8.8.8.8 1.1.1.1 0.0.0.0
3232235777
168454180
134744072
16843009
0

Another version differently golfed: 65
v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]

Sample:
ip2int() {
    v=('|%d<<'{24,16,8,0});printf -vv "${v[*]}" ${1//./ };echo $[0$v]
}

ip2int 255.255.255.255
4294967295
ip2int 10.10.104.36
168454180

In a loop (+14): 82
ip2int() {
    for i;do
        v=('|%d<<'{24,16,8,0})
        printf -vv "${v[*]}" ${1//./ }
        echo $[0$v]
    done
}

* or a little more ugly: 70*
v=('|%d<<'{24,16,8});printf -vv "${v[*]}" ${1//./ };echo $[0${v%<<2*}]

where printf give some string like |192<<24 |168<<16 |1<<8|1<<24 |0<<16 |0<<8 we have to cut at last <<2....
golfed with mapfile, longer: 68
ip2int() {
    mapfile -td. i<<<$1;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o
}

or with loop: 82
ip2int() {
    for a;do
      mapfile -td. i<<<$a;for((a=o=0;a<4;o+=i[a]<<(3-a++)*8)){ :;};echo $o
    done
}

could you add a brief explanation?  i've been trying to get into bash golfing and i don't follow what's happening with the set -- part.  thanks.

@Jonah : set -- foo bar will populate $@ with foo as $1 and bar as $2.

@Jonah Added new version

New version! more golfed, -1 char!!

Fun: Try to look content of $_ after running echo $[_=32,\printf "%d<<(_-=8)|" ${1//./ }`0]` ;-)

Managed to shave 19 characters off this. For your existing solution though, it could be shorter without meaningful refactoring; set, at least on my system, doesn't need the -- argument when what follows can't be mistaken for other switches (and plain integers can't be), so you second shortest solution can easily shave three characters (a space + --) to get it down to 44.

AWK in ~47 chars
First-timer here...  Um, not sure how to count this, but without the 'echo' it's 47 chars in AWK.  (Not exactly bogey golf, but it's in the hole.)
echo $addr | /bin/awk -F\. '{print $1*16777216+$2*65536+$3*256+$4}'

Full day early for #tbt, too, so I actually met a schedule!!!  *8-)
Banner day.

Welcome!  You'd only count the body of what you'd put into an awk script.  See this answer.  In your case you'd count only {print $1*16777216+$2*65536+$3*256+$4}.  Of course you'd have to move the field separator into the program, rather than specifying it as a flag.

Golfscript - 21 chars
{'.'/{~}%{\256*+}*}:f

+1 Good solid solution. Don't you wish GolfScript provides bit-shifting operators? ;-) (Though, darned if I know which symbols they should be bound to.)

Python 56 45
c=lambda x:eval('((('+x.replace('.','<<8)+'))

C++ - lots of chars
#include <boost/algorithm/string.hpp>
#include <string>
#include <vector>
uint f(std::string p)
{
        std::vector<std::string> x;
        boost::split(x,p,boost::is_any_of("."));
        uint r=0;
        for (uint i = 0; i < x.size(); i++)
                r=r*256+atoi(x[i].c_str());
        return r;
}

@George Edison: using boost helps to get down with the numbers of chars? :)

PowerShell 66 61
Variation on Joey's answer:
filter I{([ipaddress](($_-split'\.')[3..0]-join'.')).address}

PS C:\> '192.168.1.1' | I
3232235777
PS C:\> '10.10.104.36' | I
168454180
PS C:\> '8.8.8.8' | I
134744072

Argh, I must have been stupid to have missed that ...

Powershell, 47 43 bytes
$args-split'\.'|%{$r=([long]$r-shl8)+$_};$r

Test script:
$f = {

$args-split'\.'|%{$r=([long]$r-shl8)+$_};$r

}

@(
    ,("192.168.1.1",3232235777)
    ,("10.10.104.36",168454180)
    ,("8.8.8.8",134744072)
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

Output:
True: 3232235777
True: 168454180
True: 134744072

Windows PowerShell, 70
Naïve approach:
filter I{[int[]]$x=$_-split'\.'
$x[0]*16MB+$x[1]*64KB+$x[2]*256+$x[3]}

With using System.Net.IPAddress: 76
filter I{([ipaddress]($_-replace('(.+)\.'*3+'(.+)'),'$4.$3.$2.$1')).address}

Test:
> '192.168.1.1'|I
3232235777

JavaScript (45 characters)
Requires support for the .reduce() Array method introduced in ES5 and arrow functions.
f=(x)=>x.split('.').reduce((p,c)=>p<<8|c)>>>0

Huh... I didn't know >>> worked like that (converting to unsigned 32 bit integer)

Befunge-93 - 36 characters
&"~"2+::8****&884**:**&884***&++++.@

Perl : DIY ( for oneliners. )(40)
$j=3;$i+=($_<<($j--*8))for split/\./,$x;

# Use value in $i
DIY Function(65):
sub atoi{my($i,$j)=(0,3);$i+=($_<<($j--*8))for split'.',shift;$i}

You can split by a string, so you save a character by using split'.' rather than split/\./

With the function version, yes, but the inline version no, because you'd need split q{.} to get around the need to escape shell quotes :/

Haskell - 14 chars
(.) a=(256*a+)

usage in GHCi:
Prelude> let (.) a=(256*a+)
Prelude> 192. 168. 0. 1
3232235521

The only problem is that you have to put spaces left or right of the dot, otherwise the numbers will be interpreted as floating point.

mind adding a brief explanation?

the dot infix operator is redefined to do the computation, very smart indeed!

This is very clever, but it doesn't use the correct input format (because of the spaces)

C# – 77 chars
Func<string,uint>F=s=>s.Split('.').Aggregate(0u,(c,b)=>(c<<8)+uint.Parse(b));

05AB1E, 5 bytes
'.¡₁β

Try it online!

dude people are such ninjas

C# - 120 Characters
float s(string i){var o=i.Split('.').Select(n=>float.Parse(n)).ToList();return 16777216*o[0]+65536*o[1]+256*o[2]+o[3];}

My first code golf - be gentle ;)

You can remove the spaces around your first '='. However, your main problem is int overflow ;). Remember, an IP address takes up 4 full bytes.

@Nellius - quite right. I didn't even think of checking that, basically checked on compile. Thanks, will fix now.

D: 84 Characters
uint f(S)(S s)
{
    uint n;
    int i = 4;

    foreach(o; s.split("."))
        n += to!uint(o) << 8 * --i;

    return n;
}

i don't know D so forgive me if it's whitespace sensitive like python, but this doesn't look golfed.  can you remove the double line breaks or the line breaks between semi-colon terminated statements?

Python 3.2 (69)
sum((int(j)*4**(4*i)) for i,j in enumerate(input().split('.')[::-1]))

PHP (no builtins/eval) - 54
<foreach(explode(".",$argv[1])as$b)$a=@$a<<8|$b;echo$a;

Shouldn't this open with <?php, not just <?

@TRiG, I believe you can change the PHP opening delimiter in the config file. Useful in this case.

@Xeoncross. Ah. Neat. I might try that one day, just to mess with my workmates' heads.

Perl, 14 characters:
sub _{unpack'L>',pop}

# Example usage
print _(10.10.104.36) # prints 168454180

How do you make that 14 characters? I count 21.

Jelly, 6 bytes
ṣ”.Vḅ⁹

Try it online!
How it works
ṣ”.Vḅ⁹  Main link (monad). Input: string
ṣ”.     Split at dots
   V    Convert to numbers
    ḅ⁹  Convert base 256 to integer

Stax, 9 bytes
üL▼ü╛tΓi╨

Run and debug it

Perl 6, 16 bytes
{:256[m:g/\d+/]}

Try it online!

C (gcc) -m32 / POSIX, 33 bytes
f(a){inet_aton(a,&a);a=ntohl(a);}

Try it online!
On a big-endian platform, you could simply define a macro with -Df=inet_aton for 13 bytes.

Bash, 27 bytes
echo $[${1//./<<32-++i*8|}]

Try it online!
At the cost of 1 character, this can avoid depending on the state of i:
echo $[i=4,${1//./<<--i*8|}]

Dramatic improvement on existing bash solution (46 characters at time of writing).

Well seen and clever! By using integer: declare -i i;i="i=4,${1//./<<--i*8|}" will assign integer value to $i! Nice!

Not shorter variant: echo $[i=3,${1//./<<i--*8|}]

K (ngn/k), 10 bytes
256/.'"."\

Try it online!

"."\ split string input on .'s
.' convert each string to its integer
256/ convert from base-256

Powershell - 53
Variation on Ty Auvil's answer, which is a variation on Joey's answer:
%{([ipaddress]($_.split('.')[3..0]-join'.')).address}
PS C:\> '192.168.1.1' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
3232235777
PS C:\> '10.10.104.36' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
168454180
PS C:\> '8.8.8.8' | %{([ipaddress]($_.split('.')[3..0]-join'.')).address}
134744072

I would have just made a suggestion in the comments, but not enough rep.

ASM - 98 byte executable (WinXP command shell), about 485 characters
Assemble using A86. Badly formed IP addresses generate undefined output.
    mov si,82h
    mov di,10
    mov bp,l3
    fldz
    push l2
    push l0
    push l0
    push l0
 l0:xor ax,ax
    xor cx,cx
 l1:add ax,cx
    mov [bp+di],ax
    mul di
    mov cx,ax
    lodsb
    sub al,'0'
    jnc l1
    fild w[bp]
    fmulp
    fild w[bp+di]
    faddp
    ret
 l2:fbstp [si]
    mov bx,di
    mov di,bp
 l4:dec bx
    jz l5
    mov al,[si+bx-1]
    aam 16
    add ax,'00'
    xchg al,ah
    stosw
    jmp l4
 l5:mov al,'$'
    stosb
    lea di,[bp-1]
 l6:inc di
    cmp b[di],'0'
    je l6
 l7:cmp b[di],al
    jne l8
    dec di
 l8:mov dx,di
    mov ah,9
    int 21h
    ret
 l3:dw 256

C (91)
Not going to win anyway, so I tried to be a bit creative.
Tested on 32-bit GCC 4.4.3.
main(a,c,b)char**c,*b;{c=c[1];for(b=&a+1;c=strtok(c,".");c=0)*--b=atoi(c);printf("%u",a);}

Scala 59 chars:
def f(i:String)=(0L/:i.split("\\.").map(_.toInt))(_*256+_)

Perl with builtins (35):
unpack"N",pack"C4",split/\./,shift;

Perl without builtins (42):
split/\./,shift;$s+=$_<<@_*8while$_=shift;

Python (No eval) - 67
c=lambda x:long(''.join(["%02X"%long(i) for i in x.split('.')]),16)

can you not shorten it a few more characters by using int() instead of long()?

Mathematica, 53 chars
f=FromDigits;f[f/@StringSplit[InputString[],"."],256]

Java 8, 83 bytes
i->{long u=0;for(int j=0;j<4;)u+=new Long(i.split("\\.")[j])<<(24-8*j++);return u;}
Try it online!
Could have saved 10 bytes by moving the initialisation of u and j "up" a level but I'm not entirely sure that's allowed so I went for the safe version of my solution.

Burlesque - 11 bytes
'.;;ri256ug

'.;;           split by `.`
    ri         read integer
      256ug    undigits base 256

Try it online.

J, 21 bytes
[:256&#.[:".;._1'.'&,

Try it online!
explanation
[: 256&#. [: ".;._1 '.'&,
[: 256&#.                   NB. assuming a base 256 list,
                            NB. convert the following to decimal:
                    '.'&,   NB. the input with a dot appended
          [: ".;._1         NB. split at dots and converted to ints

Jelly, 13 bytes
4Ḷ⁹*U
ṣ”.V×¢S

Try it online!
I don't think Jelly has a builtin for this. At least, I couldn't find one.

APL(NARS), 16 chars, 32 bytes
{256⊥⍎¨⍵⊂⍨⍵≠'.'}

test
  f←{256⊥⍎¨⍵⊂⍨⍵≠'.'}
  f¨'192.168.1.1' '10.10.104.36' '8.8.8.8'
3232235777 168454180 134744072

Japt, 10 4 bytes
nG²o

Try it
 G       :16
  ²      :Squared
   o     :Range [0,G²)
n        :Convert input string from that base to base-10 integer

Kotlin, 50 bytes
{it.split(".").fold(0L){a,v->v.toInt()+(a shl 8)}}

Try it online!

min, 53 bytes
"." split 3 :a (int 256 a pow * a 1 - @a int) map sum

Takes IP address as string on stack. Leaves the converted number on top of stack.

Pxem, Filename: 58 bytes + Content: 0 bytes = 58 bytes.

Filename (escaped): ._\377\001.+.c.c.!.!.!.i.s._\377\001.+.c.!.!.+.i.s._\377\001.+.!.+.i.s._.+.n
Content: empty

Problem is that my implementation of Pxem supports literal value up to 255; needed to make greatee values by myself.
Usage
Via stdin/stdout. Accepts only one input at once.
Try it online!

Pinecone, 266 bytes
u:IntArray:4;s:"".input;k:IntArray:s.len;k.set:0,-1;n:1
i:0|i<s.len|i:i+1@((s.sub:i,i+1)="."?(k.set:n,i;n:n+1))k.set:n,s.len;i:1|i<n+1|i:i+1@(j:s.sub:((k.get:i-1)+1),(k.get:i)u.set:(i-1),(j.Int))print:((u.get:0)*16777216)+((u.get:1)*65536)+((u.get:2)*256)+(u.get:3)

Thunno 2, 5 bytes
'./ɠḋ

Try it online!
Explanation
'./ɠḋ  '# Implicit input
'./    '# Split it on "."s
   ɠḋ   # Convert from base-256
        # Implicit output

Python 3.11+ (no eval/built-in libraries), 47 bytes
c=lambda x:0 .from_bytes(map(int,x.split('.')))

As of 3.11, int.from_bytes implicitly uses big-endian byte order. 0. from_bytes is shorter than int.from_bytes, and works just fine (since from_bytes is a class method, it works the same when called on an instance; the space is needed to avoid 0. being interpreted as a float).
Attempt This Online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

authors: Andrei Андрей Листочкин

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Build an engine for a maze game
This is a follow up of Print a maze question. If you like this question, please add more maze generation algorithms ;).
For this task you'll have to implement a game engine for one player who must find the treasure in a maze and get out of the dungeon.
The engine starts by reading the maze from standard input followed by a line containing a . (dot) a file given as argument in the command line. Next the player @ is placed in a random location on the map. Then engine starts interacting with the player through standard io:
Commands from engine to player:

continue: Game not finished. The surroundings are printed followed by a .. Player is represented by @ character. Unobservable cells are represented by ?.
finished: Game finished. The number of steps is printed and the game stops.

Commands from player to engine:

north: Moves player up.
south: Moves player down.
west: Move player left.
east: Move player right.

Any invalid command (such as hitting a wall) from player is ignored, but still counted. You are free to define the surroundings to your liking.

Points for the shortest code.
Points for complex surroundings (e.g. print large regions and replace cells that are not visible by ?).
No points for code that doesn't respect the io format

Example:
In this example the surroundings is defined as the 3x3 cell with the player in the middle.
$ cat maze
+-+-+
  |#|
|   |
+---+
$ python engine.py maze
 |#
 @
---
.
east
|#|
 @|
--+
.
north
+-+
|@|
  |
.
south
|#|
 @|
--+
.
west
 |#
 @
---
.
west
  |
|@
+--
.
north
+-+
 @|
|
.
west
finished
7

@Alexandru: What are we using to generate our mazes? Can we use other peoples maze algorithms (obviously with due credit)? Or must we complete your first assignment?

@snmcdonald: Fixed typo. Use other people's mazes. Remember that the engine reads the maze from standard input.

This blog has excellent articles on maze generation using various and mixed algorithms
http://weblog.jamisbuck.org/
Check out the growing tree algorithm in-particular
http://weblog.jamisbuck.org/2011/1/27/maze-generation-growing-tree-algorithm

I'm confused as to how both the maze and the user interaction come from standard input.  Is the user supposed to type in his maze and then solve it?  Kinda defeats the purpose of only showing a portion of the maze...

You can build an app (this task is left for another question) on top of it to separate maze input from commands input.

I was thinking about trying this one---maybe as a curses exercise---but I find the rigid specifications for the interaction environment unappealing (I mean, why "continue" and not just a prompt?!? Why 4--5 character directions; I want to play nethack, man!) and the "both parts on the standard input" requirement to be nonsensical.

@dmckee: It easier to interact with an AI player. I will change to read the maze from file.

C99, 771 characters
#include <ncurses.h>
#include <string.h>
#define MIN(A,B) (A<B?A:B)
#define MAX(A,B) (A>B?A:B)
#define T(C,X,Y) case C:if((m[x+X][y+Y]==' ')||(m[x+X][y+Y]=='#'))x+=X,y+=Y;s++;break;
char m[24][81],M[24][81];int i,j,I=0,J,x,y,s=0;
int main(int c,char**v){FILE*f=fopen(v[1],"r");
for(I=0;fgets(m[I],80,f);I++)J=MAX(J,strlen(m[I]));
J--;f=fopen("/dev/random","r");do{x=fgetc(f)%I;y=fgetc(f)%J;}
while(m[x][y]!=' ');initscr();curs_set(0);do{
switch(c){T('e',0,1)T('n',-1,0)T('s',1,0)T('w',0,-1)}
for(i=MAX(0,x-1);i<MIN(x+2,I);i++)for(j=MAX(0,y-1);j<MIN(y+2,J);j++)M[i][j]=1;
for(i=0;i<I;i++)for(j=0;j<J;j++)mvaddch(i,j,M[i][j]?m[i][j]:'?');
mvaddch(x,y,'@');refresh();}while((m[x][y]!='#')&&(c=getch())!='q');
if(m[x][y]=='#')mvprintw(I,0,"Finished in %d steps!",s),getch();endwin();}

Requires and makes use of ncurses. Only one macroization for length, and the N and M macros are to replace the missing minimum and maximum opperators, and I don't think there is much more to do on that.
It assumes the input maze does not exceed 80 characters wide, and that the a maze filename has been passed on the command-line, and that the number of parameters is low enough that the initial value of c isn't a movement command.

Deviates from the standard in that it takes single character direction commands as the lowercase first letter of the ones suggested.
Does show unknown regions as '?'s.

More readable with comments:
#include <ncurses.h>
#include <string.h>

#define MIN(A,B) (A<B?A:B)/*unsafe,but short*/
#define MAX(A,B) (A>B?A:B)/*unsafe,but short*/
// #define MAX(A,B) ((_A=A)>(_B=B)?_A:_B) /* safe but verbose */
#define T(C,X,Y) case C:if((m[x+X][y+Y]==' ')||(m[x+X][y+Y]=='#'))x+=X,y+=Y;s++;break;
char m[24][81],M[24][81];/* [m]ap and [M]ask; NB:mask intialized by default */
int i,j, /* loop indicies over the map */
  I=0,J, /* limits of the map */
  x,y,   /* player position */
  s=0;   /* steps taken */
int main(int c,char**v){
  FILE*f=fopen(v[1],"r"); /* fragile, assumes that the argument is present */
  /* Read the input file */
  for(I=0;fgets(m[I],80,f);I++)J=MAX(J,strlen(m[I])); /* Read in the map */
  J--;
  /* note that I leak a file handle here */
  f=fopen("/dev/random","r");
  /* Find a open starting square */
  do{
    x=fgetc(f)%I; /* Poor numeric properties, but good enough for code golf */
    y=fgetc(f)%J;
  } while(m[x][y]!=' ');
  /* setup curses */
  initscr(); /* start curses */
  //  raw();     /* WARNING! intercepts C-c, C-s, C-z, etc...
  //          * but shorter than cbreak()
  //          */
  curs_set(0); /* make the cursor invisible */
  /* main loop */
  do {
    switch(c){
      T('e',0,1)
      T('n',-1,0)
      T('s',1,0)
      T('w',0,-1)
    }
    /* Update the mask */
    for(i=MAX(0,x-1);i<MIN(x+2,I);i++)
      for(j=MAX(0,y-1);j<MIN(y+2,J);j++)
    M[i][j]=1;
    /* draw the maze as masked */
    for(i=0;i<I;i++)
      for(j=0;j<J;j++)
    mvaddch(i,j,M[i][j]?m[i][j]:'?');
    /* draw the player figure */
    mvaddch(x,y,'@');
    refresh(); /* Refresh the display */
  } while((m[x][y]!='#')&&(c=getch())!='q');
  if(m[x][y]=='#')mvprintw(I,0,"Finished in %d steps!",s),getch();
  endwin();
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/


text:
Implement a Brute Force Sudoku Solver
Implement the shortest Sudoku solver using guessing. Since I have received a few request I have added this as an alternative question for those wishing to implement a brute force sudoku solver.
Sudoku Puzzle:
 | 1 2 3 | 4 5 6 | 7 8 9
-+-----------------------
A|   3   |     1 |
B|     6 |       |   5
C| 5     |       | 9 8 3
-+-----------------------
D|   8   |     6 | 3   2
E|       |   5   |
F| 9   3 | 8     |   6
-+-----------------------
G| 7 1 4 |       |     9
H|   2   |       | 8
I|       | 4     |   3

Answer:
 | 1 2 3 | 4 5 6 | 7 8 9
-+-----------------------
A| 8 3 2 | 5 9 1 | 6 7 4
B| 4 9 6 | 3 8 7 | 2 5 1
C| 5 7 1 | 2 6 4 | 9 8 3
-+-----------------------
D| 1 8 5 | 7 4 6 | 3 9 2
E| 2 6 7 | 9 5 3 | 4 1 8
F| 9 4 3 | 8 1 2 | 7 6 5
-+-----------------------
G| 7 1 4 | 6 3 8 | 5 2 9
H| 3 2 9 | 1 7 5 | 8 4 6
I| 6 5 8 | 4 2 9 | 1 3 7

Rules:

Assume all mazes are solvable by logic only.
All input will be 81 characters long. Missing characters will be 0.
Output the solution as a single string.
The "grid" may be stored internally however you wish.
The solution must using a brute force guessing solution.
Solutions should solve within a reasonable time limit.

Example I/O:
>sudoku.py "030001000006000050500000983080006302000050000903800060714000009020000800000400030"
832591674496387251571264983185746392267953418943812765714638529329175846658429137

How can the input be 27 characters long? It needs to be 81 characters long - 9 rows x 9 columns. That's what your example does too. Also, I assume that "missing characters will be 0" means that if the number of characters is less than 81, then the zeroes go on the end?

Oh, wait. I get the missing characters will be 0 bit. Duh. Those are the ones that need to be guessed. In any case, the number of characters does need to be 81, not 27.

it seems rules 5 and 6 kinda conflict....

k (72 bytes)
Credit for this goes to Arthur Whitney, creator of the k language.
p,:3/:_(p:9\:!81)%3
s:{*(,x)(,/{@[x;y;:;]'&21=x[&|/p[;y]=p]?!10}')/&~x}

Python, 188 bytes
This is a further shortened version of my winning submission for CodeSprint Sudoku, modified for command line input instead of stdin (as per the OP):
def f(s):
 x=s.find('0')
 if x<0:print s;exit()
 [c in[(x-y)%9*(x/9^y/9)*(x/27^y/27|x%9/3^y%9/3)or s[y]for y in range(81)]or f(s[:x]+c+s[x+1:])for c in'%d'%5**18]
import sys
f(sys.argv[1])

If you're using Python 2, '%d'%5**18 can be replaced with `5**18` to save 3 bytes.
To make it run faster, you can replace '%d'%5**18 with any permutation of '123456789' at a cost of 1 byte.
If you want it to accept the input on stdin instead, you can replace import sys;f(sys.argv[1]) with f(raw_input()), bringing it down to 177 bytes.
def f(s):
 x=s.find('0')
 if x<0:print s;exit()
 [c in[(x-y)%9*(x/9^y/9)*(x/27^y/27|x%9/3^y%9/3)or s[y]for y in range(81)]or f(s[:x]+c+s[x+1:])for c in'%d'%5**18]
f(raw_input())

EDIT: Here's a link to a more detailed walkthrough.

Python, 197 characters
def S(s):
 i=s.find('0')
 if i<0:print s;return
 for v in'123456789':
  if sum(v==s[j]and(i/9==j/9or i%9==j%9or(i%9/3==j%9/3and i/27==j/27))for j in range(81))==0:S(s[:i]+v+s[i+1:])
S(raw_input())

Perl, 120 bytes
Oh, I remember golfing that back in 2008...
And it in fact stopped working in perl 5.12 since implicit setting of @_ by split was removed then. So only try this on a sufficiently old perl.
Run with the input on STDIN:
sudoku.pl <<< "030001000006000050500000983080006302000050000903800060714000009020000800000400030"

sudoku.pl:
${/[@_[map{$i-($i="@-")%9+$_,9*$_+$i%9,9*$_%26+$i-$i%3+$i%9-$i%27}0..8%split""]]/o||do$0}for$_=$`.$_.$'.<>,/0/||print..9

It's Clarke's third law, but in reverse!

Answer in D:
import std.algorithm;
import std.conv;
import std.ascii;
import std.exception;
import std.stdio;

void main(string[] args)
{
    enforce(args.length == 2, new Exception("Missing argument."));
    enforce(args[1].length == 81, new Exception("Invalid argument."));
    enforce(!canFind!((a){return !isDigit(to!dchar(a));})
                     (args[1]),
                      new Exception("Entire argument must be digits."));

    auto sudoku = new Sudoku(args[1]);
    sudoku.fillIn();

    writeln(sudoku);
}

class Sudoku
{
public:

    this(string str) nothrow
    {
        normal = new int[][](9, 9);

        for(size_t i = 0, k =0; i < 9; ++i)
        {
            for(size_t j = 0; j < 9; ++j)
                normal[i][j] = to!int(str[k++]) - '0';
        }

        reversed = new int*[][](9, 9);

        for(size_t i = 0; i < 9; ++i)
        {
            for(size_t j = 0; j < 9; ++j)
                reversed[j][i] = &normal[i][j];
        }

        boxes = new int*[][](9, 9);
        indexedBoxes = new int*[][][](9, 9);

        for(size_t boxRow = 0, boxNum = 0; boxRow < 3; ++boxRow)
        {
            for(size_t boxCol = 0; boxCol < 3; ++boxCol, ++boxNum)
            {
                for(size_t i = 3 * boxRow, square = 0; i < 3 * (boxRow + 1); ++i)
                {
                    for(size_t j = 3 * boxCol; j < 3 * (boxCol + 1); ++j)
                    {
                        boxes[boxNum][square++] = &normal[i][j];
                        indexedBoxes[i][j] = boxes[boxNum];
                    }
                }
            }
        }
    }

    void fillIn()
    {
        fillIn(0, 0);
    }

    @property bool valid()
    {
        assert(full);

        for(size_t i = 0; i < 9; ++i)
        {
            for(int n = 1; n < 10; ++n)
            {
                if(!canFind(normal[i], n) ||
                   !canFind!"*a == b"(reversed[i], n) ||
                   !canFind!"*a == b"(boxes[i], n))
                {
                    return false;
                }
            }
        }

        return true;
    }

    override string toString() const
    {
        char[81] retval;

        for(size_t i = 0, k =0; i < 9; ++i)
        {
            for(size_t j = 0; j < 9; ++j)
                retval[k++] = to!char(normal[i][j] + '0');
        }

        return to!string(retval);
    }

private:

    @property bool full()
    {
        for(size_t i = 0; i < 9; ++i)
        {
            if(canFind(normal[i], 0))
                return false;
        }

        return true;
    }

    bool fillIn(size_t row, size_t col)
    {
        if(row == 9)
            return valid;

        size_t nextRow = row;
        size_t nextCol = col + 1;

        if(nextCol == 9)
        {
            nextRow = row + 1;
            nextCol = 0;
        }

        if(normal[row][col] == 0)
        {
            for(int n = 1; n < 10; ++n)
            {
                if(canFind(normal[row], n) ||
                   canFind!"*a == b"(reversed[col], n) ||
                   canFind!"*a == b"(indexedBoxes[row][col], n))
                {
                    continue;
                }

                normal[row][col] = n;

                if(fillIn(nextRow, nextCol))
                    return true;
            }

            normal[row][col] = 0;

            return false;
        }
        else
            return fillIn(nextRow, nextCol);
    }

    int[][] normal;
    int*[][] reversed;
    int*[][] boxes;
    int*[][][] indexedBoxes;
}

With the sample input, it takes .033s on my Phenom II X6 1090T when compiled with dmd -w (i.e. without optimizations), and it takes .011s when compiled with dmd -w -O -inline -release (i.e. with optimizations).

Perl, 235 chars
$_=$s=<>;$r=join$/,map{$n=$_;'.*(?!'.(join'|',map+($_%9==$n%9||int($_/9)==int($n/9)||int($_/27)==int($n/27)&&int($_/3%3)==int($n/3%3)and$_<$n?'\\'.($_+1):$_>$n&&substr$s,$_,1)||X,@a).')(.).*'}@a=0..80;s!.!($&||123456789).$/!eg;say/^$r/

This is a golfed version of something I posted many years ago to the Fun With Perl mailing list: a sudoku-solving regexp.
Basically, it mangles the input into 81 lines, each containing all the numbers that could occur in the corresponding square.  It then constructs a regexp to match one number from each line, using backreferences and negative lookahead assertions to reject solutions that violate the row, column or region constraints.  Then it matches the string against the regexp, letting Perl's regexp engine do the hard work of trial and backtracking.
Astonishingly, it's possible to create a single regexp that works for any input, like my original program does.  Unfortunately, it's quite slow, so I based the golfed code here on the hardcoded-givens version (found later in the FWP thread), which tweaks the regexp to reject early any solutions that it knows will later violate a constraint.  This makes it reasonably fast for easy to moderate level sudokus, although particularly hard ones can still take a rather long time to solve.
Run the code with perl -M5.010 to enable the Perl 5.10+ say feature.  The input should be given on standard input, and the solution will be printed to standard output; example:
$ perl -M5.010 golf/sudoku.pl
030001000006000050500000983080006302000050000903800060714000009020000800000400030
832591674496387251571264983185746392267953418943812765714638529329175846658429137

J, 103
'p n'=:(;#)I.0=a=:("."0)Y
((a p}~3 :'>:?n#9')^:([:(27~:[:+/[:(9=#@~.)"1[:,/(2 2$3),;.3],|:,])9 9$])^:_)a

expected run time: O(gazillion billion years)

And why is the expected run time "O(gazillion billion years)"? (shouldn't that be just "gazillion billion years" without the O?

When I saw this question I immediatly knew that J is going to crush this one. There has to be a way to make this shorter than K.

@Quincunx, strictly speaking, it's a wrong use of big-O; the "joke" was supposed to read "constant run time, asymptotically gazillion billion years".

@koko, I couldn't find something better but I'm still working on it.

1-liner coffee-script
solve = (s, c = 0) -> if c is 81 then s else if s[x = c/9|0][y = c%9] isnt 0 then solve s, c+1 else (([1..9].filter (g) -> ![0...9].some (i) -> g in [s[x][i], s[i][y], s[3*(x/3|0) + i/3|0][3*(y/3|0) + i%3]]).some (g) -> s[x][y] = g; solve s, c+1) or s[x][y] = 0
Here is the bigger version with sample usage:
solve = (sudoku, cell = 0) ->
  if cell is 9*9 then return sudoku

  x = cell%9
  y = (cell - x)/9

  if sudoku[x][y] isnt 0 then return solve sudoku, cell+1

  row = (i) -> sudoku[x][i]
  col = (i) -> sudoku[i][y]
  box = (i) -> sudoku[x - x%3 + (i - i%3)/3][y - y%3 + i%3]

  good = (guess) -> [0...9].every (i) -> guess not in [row(i), col(i), box(i)]

  guesses = [1..9].filter good

  solves = (guess) -> sudoku[x][y] = guess; solve sudoku, cell+1

  (guesses.some solves) or sudoku[x][y] = 0

sudoku = [
  [1,0,0,0,0,7,0,9,0],
  [0,3,0,0,2,0,0,0,8],
  [0,0,9,6,0,0,5,0,0],
  [0,0,5,3,0,0,9,0,0],
  [0,1,0,0,8,0,0,0,2],
  [6,0,0,0,0,4,0,0,0],
  [3,0,0,0,0,0,0,1,0],
  [0,4,0,0,0,0,0,0,7],
  [0,0,7,0,0,0,3,0,0]
]
console.log if solve sudoku then sudoku else 'could not solve'

Could be shortened by shortening solve, removing lots of whitespace (I know it's significant, but in many places it could be removed), using symbols instead of words (like != instead of isnt), using indentation instead of then keyword, replacing [0...9] with [0..8].

D (322 chars)
For each unsolved square it builds an array of available options and then loops over it.
import std.algorithm,std.range,std.stdio;void main(char[][]args){T s(T)(T p){foreach(i,ref c;p)if(c<49){foreach(o;"123456789".setDifference(chain(p[i/9*9..i/9*9+9],p[i%9..$].stride(9),p[i/27*27+i%9/3*3..$][0..21].chunks(3).stride(3).joiner).array.sort)){c=o&63;if(s(p))return p;}c=48;return[];}return p;}s(args[1]).write;}

with whitespace:
import std.algorithm, std.range, std.stdio;

void main(char[][] args) {
    T s(T)(T p) {
        foreach (i, ref c; p) if (c < 49) {
            foreach (o; "123456789".setDifference(chain(
                    p[i/9*9..i/9*9+9],
                    p[i%9..$].stride(9),
                    p[i/27*27+i%9/3*3..$][0..21].chunks(3).stride(3).joiner
                ).array.sort))
            {
                c = o&63;
                if (s(p)) return p;
            }
            c=48;
            return [];
        }
        return p;
    }
    s(args[1]).write;
}

Clojure - 480 bytes
The size exploded, but atleast it's a pretty number. I think it could be improved a lot by using just 1D-vector. Anyways, the test case takes a little under four seconds on my laptop. I thought it would be fitting to define a function, as it is a functional language after all.
(defn f[o &[x y]](if x(if(> y 8)(apply str(map #(apply str %)o))(first(for[q[(o y)]v(if(=(q x)0)(range 1 10)[(q x)])d[(assoc o y(assoc(o y)x v))]s[(and(every? true?(concat(for[i(range 9)](and(or(not=((d y)i)v)(= i x))(or(not=((d i)x)v)(= i y))))(for[m[#(+ %2(- %(mod % 3)))]r[(range 3)]a r b r c[(m y b)]e[(m x a)]](or(and(= e x)(= c y))(not=((d y)x)((d c)e))))))(f d(mod(+ x 1)9)(if(= x 8)(+ 1 y)y)))]:when s]s)))(f(vec(for[a(partition 9 o)](vec(map #(Integer.(str %))a))))0 0)))

Examples:
(f "030001000006000050500000983080006302000050000903800060714000009020000800000400030")
=> "832591674496387251571264983185746392267953418943812765714638529329175846658429137"
(f "004720900039008005001506004040010520028050170016030090400901300100300840007085600")
=> "654723981239148765871596234743819526928654173516237498482961357165372849397485612"

A slightly ungolfed (and prettier) version:
(defn check-place [o x y v]
  (and (every? true? (for [i (range 9)]
                       (and (or (not= ((o y) i) v) (= i x))
                            (or (not= ((o i) x) v) (= i y)))))
       (every? true?
         (for [r [(range 3)]
               a r
               b r
               c [(+ b (- y (mod y 3)))]
               d [(+ a (- x (mod x 3)))]]
           (or (and (= d x) (= c y)) (not= ((o y) x) ((o c) d)))))))

(defn solve-sudoku [board & [x y]]
  (if x
    (if (> y 8)
      (apply str (map #(apply str %) board))
      (first
        (for [v (if (= ((board y) x) 0) (range 1 10) [((board y) x)])
              :let [a (mod (+ x 1) 9)
                    b (if (= x 8) (+ 1 y) y)
                    d (assoc board y (assoc (board y) x v))
                    s (and (check-place d x y v) (solve-sudoku d a b))]
              :when s]
          s)))
    (solve-sudoku (vec (for [a (partition 9 board)]
                         (vec (map #(Integer. (str %)) a)))) 0 0)))

PowerShell, 244 242 218 215 bytes
$a=(24,24,6)*3|%{,(0..8|%{($r++)});,(0..8|%{$c%81;$c+=9});$c++;,((1,1,7)*3|%{+$q;$q+=$_});$q-=$_}
$f={param($s)$l,$r=$s-split0,2;if($p=$a|?{$l.length-in$_}){1..9|?{"$_"-notin($p|%{$s[$_]})}|%{&$f "$l$_$r"}}else{$s}}

Try it online!
The script finds all solutions for a sudoku.
Unrolled:
$a=(24,24,6)*3|%{                       # array of indexes for a sudoku...
    ,(0..8|%{($r++)})                   # rows
    ,(0..8|%{$c%81;$c+=9});$c++         # columns
    ,((1,1,7)*3|%{+$q;$q+=$_});$q-=$_   # and squares
}

$f = {
    param($s)

    # optional log. remove this statement in a release version.
    if($script:iter++ -lt 100 -or ($script:iter%100)-eq0){
        Write-Information ('{0}: {1,6}: {2}'-f (get-Date), $script:iter, ($s-replace0,' ')) -InformationAction Continue
    }

    $left,$right=$s-split0,2                # split by a first 0; $left.length is a position of this 0 if $s contains the 0
    if( $parts=$a|?{$left.length-in$_} ){   # get sudoku parts (rows, columns, squares) contain the position
        1..9|?{                             # try a digit
            "$_"-notin($parts|%{$s[$_]})    # all digits in these parts will be unique if parts do not contain the digit
        }|%{
            &$f "$left$_$right"             # recursive call with the digit
        } #|select -f 1                     # uncomment this to get a first result only
    }
    else{
        $s
    }

}

Test cases:
@(
    # 5 iterations, my notebook: 00:00:00, all
    # 5 iterations, my notebook: 00:00:00, first only
    , ( "832591674496387251571264983185746392267953418943812765714638529329175846658400030",
        "832591674496387251571264983185746392267953418943812765714638529329175846658429137" )

    # ~29600 iterations, my notebook: 00:01:27, all
    #  ~2100 iterations, my notebook: 00:00:10, first only
    # , ( "830001000006000050500000983080006302000050000903800060714000009020000800000400030",
    #     "832591674496387251571264983185746392267953418943812765714638529329175846658429137" )

    # ~49900 iterations, my notebook: 00:02:39, all
    # ~22400 iterations, my notebook: 00:01:20, first only
    # , ( "030001000006000050500000983080006302000050000903800060714000009020000800000400030",
    #     "832591674496387251571264983185746392267953418943812765714638529329175846658429137" )

) | % {
    $sudoku, $expected = $_
    $time = Measure-Command {
        $result = &$f $sudoku
    }
    "$($result-contains$expected): $time"
    $result
}

J, 94 bytes
Works in exactly the same way as the K version, namely with a BFS (so it shall output all solutions).
It prints spaces between output digits, but so does the K program. I’m not counting “s=:” as this is just naming the function (just like I wouldn’t count the filename in another language).
   s=: [:<@((]i.0:)}"0 _~(>:i.9)-.{&((+./ .=|:)3(],.[,@#.<.@%~)9 9#:i.81)@i.&0#])"1^:(0 e.,)@;^:_"."0

   s'030001000006000050500000983080006302000050000903800060714000009020000800000400030'
8 3 2 5 9 1 6 7 4 4 9 6 3 8 7 2 5 1 5 7 1 2 6 4 9 8 3 1 8 5 7 4 6 3 9 2 2 6 7 9 5 3 4 1 8 9 4 3 8 1 2 7 6 5 7 1 4 6 3 8 5 2 9 3 2 9 1 7 5 8 4 6 6 5 8 4 2 9 1 3 7

Perl (195 chars)
use integer;@A=split//,<>;sub R{for$i(0..80){next if$A[$i];my%t=map{$_/9==$/9||$_%9==$i%9||$_/27==$i/27&&$_%9/3==$i%9/3?$A[$_]:0=>1}0..80;R($A[$i]=$_)for grep{!$t{$_}}1..9;return$A[$i]=0}die@A}R

All credit goes to the creator here, and the explanation can be found there as well.

If you didn't write it yourself, then you should check the "Community Wiki" button.

After some research as to what that is, it doesn't look possible for me. Apparently 100 rep is needed for me to see the checkbox (see the addendum section under #2 of this post)

Hmm, wasn't aware of that requirement.