Skip to content

Instantly share code, notes, and snippets.

@YumaInaura
Last active September 12, 2018 01:14
Show Gist options
  • Save YumaInaura/beaf62eb4bffd33664dada0a398a5897 to your computer and use it in GitHub Desktop.
Save YumaInaura/beaf62eb4bffd33664dada0a398a5897 to your computer and use it in GitHub Desktop.
Ruby — Print code and result both at one time Like shell -x option ( One idea )

Ruby — Print code and result both at one time Like shell -x option ( One idea )

Points

  • write codes in Here doc
  • each line
  • eval

Script

#!/usr/bin/env ruby

commands = <<~COMMANDS
1
1.to_s
nil
1 + 1
2 * 3
[:a, :b, :c]
[1, 2, 3].map { |num| num*3 }
COMMANDS

commands.each_line do |command|
  print command.chomp
  print ' # '
  p (eval command)
end

Result

1 # 1
1.to_s # "1"
nil # nil
1 + 1 # 2
2 * 3 # 6
[:a, :b, :c] # [:a, :b, :c]
[1, 2, 3].map { |num| num*3 } # [3, 6, 9]

Versions

  • ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]

Links

#!/usr/bin/env ruby
codes = <<-CODES
1
1.to_s
nil
1 + 1
2 * 3
[:a, :b, :c]
[1, 2, 3].map { |num| num*3 }
alice = :liddle
alice
CODES
def each_codes(codes)
b = binding
codes.each_line do |code|
code.gsub!(/^\s+|\s+$/, '')
if code.empty?
print "\n"
next
end
if code =~ /^#/
puts code
else
print code
print ' # '
begin
p (b.eval code)
rescue => e
puts e.message
end
end
end
end
each_codes(codes)
## Outputs
#
# 1 # 1
# 1.to_s # "1"
# nil # nil
#
# 1 + 1 # 2
# 2 * 3 # 6
#
# [:a, :b, :c] # [:a, :b, :c]
# [1, 2, 3].map { |num| num*3 } # [3, 6, 9]
#
# alice = :liddle # :liddle
# alice # :liddle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment