summaryrefslogtreecommitdiffhomepage
path: root/ruby.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'ruby.html.markdown')
-rw-r--r--ruby.html.markdown37
1 files changed, 36 insertions, 1 deletions
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 2595d1d5..4b96b71c 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -23,6 +23,15 @@ contributors:
```ruby
# This is a comment
+=begin
+This is a multi-line comment.
+The beginning line must start with "=begin"
+and the ending line must start with "=end".
+
+You can do this, or start each line in
+a multi-line comment with the # character.
+=end
+
# In Ruby, (almost) everything is an object.
# This includes numbers...
3.class #=> Integer
@@ -172,6 +181,9 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arrays can contain different types of items.
[1, 'hello', false] #=> [1, "hello", false]
+# You might prefer %w instead of quotes
+%w[foo bar baz] #=> ["foo", "bar", "baz"]
+
# Arrays can be indexed.
# From the front...
array[0] #=> 1
@@ -247,6 +259,14 @@ else
'else, also optional'
end
+# If a condition controls invocation of a single statement rather than a block of code
+# you can use postfix-if notation
+warnings = ['Patronimic is missing', 'Address too short']
+puts("Some warnings occurred:\n" + warnings.join("\n")) if !warnings.empty?
+
+# Rephrase condition if `unless` sounds better than `if`
+puts("Some warnings occurred:\n" + warnings.join("\n")) unless warnings.empty?
+
# Loops
# In Ruby, traditional `for` loops aren't very common. Instead, these
# basic loops are implemented using enumerable, which hinges on `each`.
@@ -307,6 +327,11 @@ puts doubled
puts array
#=> [1,2,3,4,5]
+# another useful syntax is .map(&:method)
+a = ["FOO", "BAR", "BAZ"]
+a.map { |s| s.downcase } #=> ["foo", "bar", "baz"]
+a.map(&:downcase) #=> ["foo", "bar", "baz"]
+
# Case construct
grade = 'B'
@@ -402,7 +427,7 @@ def guests(&block)
end
# The 'call' method on the Proc is similar to calling 'yield' when a block is
-# present. The arguments passed to 'call' will be forwarded to the block as arugments.
+# present. The arguments passed to 'call' will be forwarded to the block as arguments.
guests { |n| "You have #{n} guests." }
# => "You have 4 guests."
@@ -413,6 +438,16 @@ def guests(*array)
array.each { |guest| puts guest }
end
+# There is also the shorthand block syntax. It's most useful when you need
+# to call a simple method on all array items.
+upcased = ['Watch', 'these', 'words', 'get', 'upcased'].map(&:upcase)
+puts upcased
+#=> ["WATCH", "THESE", "WORDS", "GET", "UPCASED"]
+
+sum = [1, 2, 3, 4, 5].reduce(&:+)
+puts sum
+#=> 15
+
# Destructuring
# Ruby will automatically destructure arrays on assignment to multiple variables.