An initial impression that I've had of Ruby which has stayed true is that there is often more than one way to do something. Just some random Ruby stuff I'm studying tonight.
Fun with Arrays
Two different ways to create an
arr1 = Array.new # =>  arr2 = 
Two different ways to push an item into an
.push 'foo' # => ['foo']  << 'foo' # => ['foo']
Array and push a
String into it
arr1 = Array.new.push 'Foobar' # => ['Foobar'] arr2 =  << 'Foobar' # => ['Foobar'] arr3 = Array.new << 'Foobar' # => ['Foobar']
It's interesting to me that these are the same two statements
Array.new << 'Foobar' Array.new.<<('Foobar')
Push all the contents of one array into another
arr1 = [1,2,3] arr2 = [4,5,6] arr1.push *arr2 # => [1,2,3,4,5,6]
This is an interesting example from the homepage
cities = %w[ Negril Bogota Caracas Paris Amsterdam Berlin] visited = %w[ Negril Amsterdam Caracas] puts "I still need to visit the following cities:", cities - visited
String into an
'foobar'.chars.to_a # => ['f','o','o','b','a','r'] 'foobar'.split(//) # => ['f','o','o','b','a','r']
String have a
<< method. With regards to
push and with
String it's a concatenator.
 << 'one' << 'two' << 'three' # => ['one', 'two', 'three'] 'one ' << 'two' # => 'one two'
See something wrong or got something to add/change? Fork this git repo and send me a pull request
If you particularly enjoy my work, I appreciate donations given with Gitcoin.co