ruby :: meaning code example

Example 1: ruby %w meaning

%w(foo bar) is a shortcut for ["foo", "bar"]. Creates an array of the strings.

Example 2: meaning of {} in ruby

When on their own, or assigning to a variable, [] creates arrays, and {} creates hashes. e.g.

a = [1,2,3] # an array
b = {1 => 2} # a hash
[] can be overridden as a custom method, and is generally used to fetch things from hashes (the standard library sets up [] as a method on hashes which is the same as fetch)
a = {1 => 2} # create a hash for example
puts a[1] # same as a.fetch(1), will print 2

Tags:

Ruby Example