Created
November 20, 2014 19:54
-
-
Save JohnB/ff9ff14d2f2a922d5199 to your computer and use it in GitHub Desktop.
List comprehension in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Inspired by https://blog.engineyard.com/2014/ruby-list-comprehension | |
module Kernel | |
def c(comprehension, &block) | |
scope = block.send(:binding) | |
if comprehension =~ /^\s*(\S.*)\s+for\s+(\S+)\s+in\s+(.*)$/ | |
amount, for_variable, in_range = $1,$2,$3 | |
scope.send(:eval, in_range).map do |value| | |
scope.send(:eval, "#{for_variable} = #{value}") | |
scope.send(:eval, "#{for_variable} = #{amount}") | |
block.call( scope.send(:eval, "#{for_variable}" ) ) | |
end | |
else | |
'no comprende!' | |
end | |
end | |
end | |
class TestHarness | |
def test | |
wacky = 2 | |
in_my_scope = 7 | |
comprehension = 'n + wacky for n in [1, 2, 3, 4, 5]' | |
result = c(comprehension) do |n| | |
n * in_my_scope | |
end | |
expected = [21, 28, 35, 42, 49] | |
puts "GIVEN: | |
wacky = 2 | |
in_my_scope = 7 | |
comprehension = 'n + wacky for n in [1, 2, 3, 4, 5]' | |
..." | |
puts "Expected: #{expected.inspect}." | |
puts "actual: #{result.inspect}." | |
puts (result == expected) ? "SUCCESS" : "** FAIL **" | |
return result == expected | |
end | |
end | |
puts "--- TESTING ---" | |
result = TestHarness.new.test | |
puts "--- end test --" | |
puts "TODO: get this to work: '[[print(str(x) for x in y] for 2 * y in xrange(1, 100)]'" | |
result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment