Skip to content

Instantly share code, notes, and snippets.

@geopet
Created February 22, 2013 18:32
Show Gist options
  • Save geopet/5015531 to your computer and use it in GitHub Desktop.
Save geopet/5015531 to your computer and use it in GitHub Desktop.
Quick example in elegance using PHP and Ruby. PHP forces us to use the bang to check for not. Ruby has `unless` which allows, in my opinion, a more fluid way to write code.
<?php
$my_array = array('apple', 'pear', 'cherry')
// If I want to find out if a value is in an array with PHP I do this:
if (in_array('apple', $my_array)) {
echo 'Apple is in the array!'; // => Apple is in the array!
}
// If I want to check if there isn't a variable in an array:
if (!(in_array('earthworm', $my_array))) {
echo 'Earthworm is not in the array!'; // => Earthworm is not in the array!
}
my_array = %w[apple pear cherry]
# In Ruby I can do this to see if something is in an array:
if my_array.include?('apple') do
puts 'Apple is in the array!' # => Apple is in the array!
end
# If I'm checking if something isn't in an array:
unless my_array.include?('earthworm') do
puts 'Earthworm is not in the array!' # => Earthworm is not in the array!
end
@geopet
Copy link
Author

geopet commented Feb 22, 2013

Something to note: I didn't do the in-line puts with the Ruby example to try and show the Ruby example more like the PHP one.

Here's another perfectly valid way of writing the Ruby example:

my_array = %w[apple pear cherry]

puts 'Apple is in the array!' if my_array.include?('apple')

puts 'Earthworm is not in the array!' unless my_array.include?('earthworm')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment