diff options
author | Per Lilja <perlilja@gmail.com> | 2015-10-21 13:28:36 +0200 |
---|---|---|
committer | Per Lilja <perlilja@gmail.com> | 2015-10-21 13:28:36 +0200 |
commit | 3f8b067a0cace44bb43bdd08561b0efc747fb26c (patch) | |
tree | 1e17c3f1968f7b2f97ea9f84ca0098224ff60786 /ruby.html.markdown | |
parent | d1a822f96c88855b2cbb649a4ea7b452e4104164 (diff) | |
parent | ef6973b13f50063462d28a96ac57e93aed40844c (diff) |
Merge pull request #1 from adambard/master
Update fork
Diffstat (limited to 'ruby.html.markdown')
-rw-r--r-- | ruby.html.markdown | 40 |
1 files changed, 38 insertions, 2 deletions
diff --git a/ruby.html.markdown b/ruby.html.markdown index 8f23b2e6..998b4bf7 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -12,7 +12,8 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] --- ```ruby @@ -39,6 +40,8 @@ You shouldn't either 10 * 2 #=> 20 35 / 5 #=> 7 2**5 #=> 32 +5 % 3 #=> 2 +5 ^ 6 #=> 3 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -106,8 +109,20 @@ placeholder = 'use string interpolation' 'hello ' + 3 #=> TypeError: can't convert Fixnum into String 'hello ' + 3.to_s #=> "hello 3" -# print to the output +# Combine strings and operators +'hello ' * 3 #=> "hello hello hello " + +# Append to string +'hello' << ' world' #=> "hello world" + +# print to the output with a newline at the end puts "I'm printing!" +#=> I'm printing! +#=> nil + +# print to the output without a newline +print "I'm printing!" +#=> I'm printing! => nill # Variables x = 25 #=> 25 @@ -154,6 +169,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can be indexed # From the front array[0] #=> 1 +array.first #=> 1 array[12] #=> nil # Like arithmetic, [var] access @@ -164,6 +180,7 @@ array.[] 12 #=> nil # From the end array[-1] #=> 5 +array.last #=> 5 # With a start index and length array[2, 3] #=> [3, 4, 5] @@ -258,6 +275,12 @@ hash.each do |key, value| puts "#{key} is #{value}" end +# If you still need and index you can use "each_with_index" and define an index +# variable +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" @@ -269,6 +292,19 @@ end #=> iteration 4 #=> iteration 5 +# There are a bunch of other helpful looping functions in Ruby, +# for example "map", "reduce", "inject", the list goes on. Map, +# for instance, takes the array it's looping over, does something +# to it as defined in your block, and returns an entirely new array. +array = [1,2,3,4,5] +doubled = array.map do |element| + element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + grade = 'B' case grade |