Q:

Printing string fields in Ruby

I have this string in the variable var:

cheese dogs cats alligators

I know I could get the second field in this string " dogs" using awk if I was on a linux command line.
> cat var | awk '{print $2}'
dogs

But how would I do this in Ruby?

A:

Ruby has a String#split method that splits on whitespace by default, returning an array whose second element can then be accessed:
irb(main):001:0> 'cheese dogs cats alligators'.split
=> ["cheese", "dogs", "cats", "alligators"]
irb(main):002:0> 'cheese dogs cats alligators'.split[1]
=> "dogs"

