Ben C.
Ben C.

Reputation: 1861

Converting between bases in Ruby

I'm trying to learn Ruby using problems from this subreddit. I'm working on a problem that's asking me to take a string containing a series of hex values separated by spaces, then convert them to binary and do some work based on the binary values. I have what looks like should be a working solution, but I'm getting errors when I run it. Here's the code:

print "enter: "

vals = gets.chomp.split

for i in 0...vals.length do
   vals[i].hex.to_s(2)!
end

vals.each {|x| puts x}

I'm getting the following error messages:

test.rb:6: syntax error, unexpected '!', expecting keyword_end
test.rb:9: syntax error, unexpected end-of-input, expecting keyword_end

From what I understand, the .hex method should return the decimal value of a hex string, and to_s(2)! should convert that integer to a binary string. Obviously, though, I'm not getting something.

Upvotes: 0

Views: 219

Answers (1)

fotanus
fotanus

Reputation: 20116

The bang after to_s is not a valid syntax on ruby. What you can have is a method ending with !, for example, chomp!. And there is no .to_s! method.

What you are looking for can be achieved by the following code:

print "enter: "

vals = gets.chomp.split

for i in 0...vals.length do
     vals[i] = vals[i].hex.to_s(2)
end

vals.each {|x| puts x}

Upvotes: 2

Related Questions