Resolve – Run a Ruby Script From Command Line Windows?

It looks like your Ruby code might not be running due to an undefined Error class and a typo (put instead of puts). Additionally, index out of range errors may occur if the input strings are too short.

Error Explanation:

String mutation error: Attempting to assign values directly to str1[3] and str2[5] may raise IndexError if the strings are not long enough.

Undefined Error class: The code raises Error, but no Error class is defined or imported, causing a NameError.

Typo in puts statement: put should be puts, leading to a NoMethodError.

Error Code:

code#!/usr/bin/env ruby

class StringSwap
def initialize(str1, str2)
raise Error unless str1.length > 4
raise Error unless str2.length > 6
temp = str1[3]
str1[3] = str2[5]
str2[5] = temp
@str1 = str1
@str2 = str2
end

def print()
puts @str1
puts @str2
end
end

def main()
puts "WHYYY"
s1 = gets.chomp
s2 = gets.chomp
obj = StringSwap.new(s1, s2)
obj.print()
end

main()

Potential Issues and Fixes

Shebang Line Issue:
The line #!/usr/bin/env ruby is typically used in Unix-like systems. On Windows, it might not affect how the script runs. You can try running it without relying on the shebang line by using:The line #!/usr/bin/env ruby is typically used in Unix-like systems. On Windows, it might not affect how the script runs. You can try running it without relying on the shebang line by using:

coderuby file.rb

Syntax Errors:
There are a couple of mistakes in your code:

  • put str1 and put str2 should be puts @str1 and puts @str2 inside the print method.
  • Error should be StandardError or a valid error type in Ruby.

Correct Code:

codeclass StringSwap
def initialize(str1, str2)
raise StandardError, "String 1 must be longer than 4 characters" unless str1.length > 4
raise StandardError, "String 2 must be longer than 6 characters" unless str2.length > 6

temp = str1[3]
str1[3] = str2[5]
str2[5] = temp

@str1 = str1
@str2 = str2
end

def print
puts @str1
puts @str2
end
end

def main
puts "WHYYY"
s1 = gets.chomp
s2 = gets.chomp
obj = StringSwap.new(s1, s2)
obj.print
end

main if __FILE__ == $0

File Encoding:
Ensure the file is saved with the correct encoding (UTF-8). Some encoding issues on Windows can prevent scripts from running properly.

Environment Setup:
Make sure Ruby is properly installed and added to your system’s PATH. Check by running:

coderuby -v

This command should display your Ruby version.

Windows Command Line vs. Terminal Issue:
If you’re using cmd, try running the script in PowerShell or Windows Terminal.

Check for Silent Failures:
Add some print statements at the start of your script to verify if it’s running at all:

Make sure Ruby is properly installed and added to your system’s PATH. Check by running:

puts "Script started!"

    By addressing the syntax issues and ensuring the correct environment setup, the script should run as expected. Let me know if it works or if the issue persists!

    Related blog posts