Permalink
Browse files

Explain ternary + if statements

  • Loading branch information...
1 parent 9ea44a9 commit b13200c8f3cd10dd66383a4ba101e4a8459b72cf @radar radar committed Sep 19, 2010
Showing with 48 additions and 0 deletions.
  1. +7 −0 code.rb
  2. +29 −0 explanations/if.md
  3. +8 −0 fixtures/if.rb
  4. +4 −0 processor.rb
View
@@ -265,6 +265,13 @@ def self.from_test_fixture(name)
end
end
+ describe "explains" do
+ it "ternary statements" do
+ code = described_class.new('code' => 'this ? that : them')
+ code.reconstruct_code.should == ">> if\nthis ? (that) : (them)"
+ end
+ end
+
describe "#reconstruct_code" do
it "inserts explanation markers" do
code = described_class.new('code' => "class Klass < Main; end")
View
@@ -0,0 +1,29 @@
+## `if` statement
+
+
+
+The `if` statement is used for when we want to conditionally run code. A common `if` syntax is this:
+
+ if condition then
+ conditional_code
+ end
+
+If `condition` in this example is not `nil` or `false` then the `conditional_code` will be executed. The `then` after the condition can be implicit and doesn't need to be there. Because this `if` is short, it can be all put on to one line:
+
+ conditional_code if condition
+
+You may also use the `else` keyword after the `if` but before the `end` to define code that should be ran if the `if` condition evaluates to `nil` or `false`:
+
+ if condition
+ conditional_code
+ else
+ alternative_code
+ end
+
+A shorter way to write this would be to use a _ternary statement_, which looks like this:
+
+ condition ? conditional_code : alternative_code
+
+In this example the `?` indicates the beginning of the code to run when the `if` evaluates to `true`. After that code, we use `:` to denote what code should be ran if the `condition` evaluates to `false`.
+
+**Please note**: `if` statements that can be condensed to one line will be output as ternary examples, where as multi-lined `if` statements will be output as such with `then` after the condition.
View
@@ -0,0 +1,8 @@
+this ? that : them
+
+if this
+ that
+ what
+else
+ them
+end
View
@@ -113,6 +113,10 @@ def process_iasgn(exp)
def process_cvdecl(exp)
mark(:variable_class) + super
end
+
+ def process_if(exp)
+ mark(:if) + super
+ end
CALLS = [:require, :attr_accessor, :attr_reader, :attr_writer, :include, :extend]

0 comments on commit b13200c

Please sign in to comment.