Last active
September 30, 2022 14:56
-
-
Save yevgenko/ba31a26f3f94961446d42ca504007582 to your computer and use it in GitHub Desktop.
Freezing random generator and capturing output of ruby script without changing original file ['jbrains/trivia', 'golden master']
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
require 'stringio' | |
def capture_stdout_string | |
io = StringIO.new | |
capture_stdout(io) do | |
yield | |
end | |
io.string | |
end | |
def capture_stdout(io) | |
original_stdout = $stdout | |
$stdout = io | |
yield | |
ensure | |
$stdout = original_stdout | |
end | |
puts 'Testing namespace protection' | |
puts | |
puts "load 'test-load.rb', true" | |
result = capture_stdout_string do | |
load 'test-load.rb', true | |
puts @foo | |
end | |
puts "@foo = #{result}" | |
puts "load 'test-load.rb', false" | |
result = capture_stdout_string do | |
load 'test-load.rb', false | |
puts @foo | |
end | |
puts "@foo = #{result}" | |
puts | |
puts 'Testing the freezing of random number generator' | |
puts | |
puts 'First Sequence:' | |
srand(7777) | |
result = capture_stdout_string do | |
load 'script.rb', true | |
end | |
puts "Result: #{result}" | |
result = capture_stdout_string do | |
load 'script.rb' | |
end | |
puts "Result: #{result}" | |
puts | |
puts 'Second Sequence' | |
## | |
# Reset sequence of random numbers | |
# To match results of first and second runs | |
# | |
# Each call to 'rand' would generate new number | |
# but the sequence is repeatable, see test-srand.rb | |
srand(7777) | |
result = capture_stdout_string do | |
load 'script.rb' | |
end | |
puts "Result: #{result}" | |
result = capture_stdout_string do | |
load 'script.rb' | |
end | |
puts "Result: #{result}" |
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
#!/usr/bin/env ruby | |
puts rand |
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
@foo = 'bar' |
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
srand 7777 | |
puts rand | |
puts rand | |
puts rand |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment