Issue
I am using this code to check if user's input (which is always number) is even or odd, but the script always return "Even"
read -p "Enter a number: " x
if ((x % 2 == 0));
then echo "Even";
else echo "Odd";
fi
I am using this test:
def solution(x)
puts("Number: #{x}")
run_shell(args: [x]).strip
end
describe "Solution" do
it "should print 'Even' for even numbers" do
[0, 2, 4, 78, 100000, 1545452, -2, -10, -123456]
.each { |x| expect(solution(x)).to eq('Even') }
end
it "should print 'Odd' for odd numbers" do
[1, 3, 5, 77, 100001, 1545455, -1, -3, -9, -12345]
.each { |x| expect(solution(x)).to eq('Odd') }
end
end
Solution
Your Ruby code passes arguments on the shell script's command line, but the shell script is looking for arguments on its standard input stream.
Because in an arithmetic context the shell treats an empty string like a 0, you get a result of always-even.
Consider reading from stdin only when you haven't been provided input on the command line:
#!/usr/bin/env bash
if [[ $1 ]]; then
x=$1
else
read -p 'Enter a number: ' x
fi
if ((x % 2 == 0)); then
echo "Even"
else
echo "Odd"
fi
Answered By - Charles Duffy Answer Checked By - Katrina (WPSolving Volunteer)