Invalid hex escape - ruby

There is my code :
var = "aa"
var2 = "bb"
var3 = "\x#{var}\x#{var2}"
And I want the "var3" to be hexadecimal.
But the error message is "Invalid hex escape". How can I fix that ?

This could help:
var3 = "#{var.hex.chr}#{var2.hex.chr}"

Your example does not work because \x has “higher priority” than string interpolation.
vars = [var, var2]
var3 = vars.pack('H*' * vars.size)
#⇒ "\xAA\xBB"
More info.

Another approach is this:
[var, var2].map { |s| '\x' + s }.join
Can you explain why you want var3 to be in that format? If it's to serialize the values, then another method might be simpler, e.g.:
require 'yaml'
[var, var2].to_yaml
# or
{ var: var, var2: var2 }.to_yaml

Lets say you want to send epoch timestamp as raw hexadecimal code, idea is simple create an array of bytes and then "pack" it (this will encode the string in the right way so it can be read and decode as hex code)
epoch_timestamp = 1631737774
epoch_hex = epoch_timestamp.to_s(16)
# epoch_hex is 4 bytes 614257a6
bytes = [epoch_hex[0..1], epoch_hex[2..3], epoch_hex[4..5], epoch_hex[6..7]]
bytes.pack('H*' * bytes.size)

Related

How to find and remove the string from string using ruby?

I want to find & remove a string from string. See the examples below,
Input1:
a = 'mangalore'
Input2
b = 'mc'
Outputs
b values should not present in a for output1 #angalore
a values should not present in b for output2 #c
Solutions: converting string a,b to array then doing a-b & b-a
it will give results. How to implement using string in ruby.
Helps appreciated!
Use String#tr:
main > 'mangalore'.tr 'mc', '#'
#⇒ "#angalore"
main > 'mc'.tr 'mangalore', '#'
#⇒ "#c"

trying to add a variables in Ruby

I'm on day one of Ruby and I can't do the most basic of things. The code below is a sample of what I am trying to do. I simply need to add the user input wit the variable. I keep getting a "can't convert float into string" error message.
The more I research a solution, the more it steers me in a different direction. Recasting variables should be pretty simple. I don't understand what i'm doing wrong.
var1 = Float("9.99")
puts "enter in your quantity"
quantity1 = gets + var1
puts "quantity1"
gets returns a string, so you need to cast it to something Numeric in order to add a float to it.
quantity = gets.to_f + var1
will work, but I suggest that you'll do some more reading.
Also you can assign var1 like this: var1 = 9.99
gets stands for get string. You need to convert that string to an integer or a float using the method .to_i (to integer) or .to_f (to float).
I would do this:
var1 = 9.99
puts "enter in your quantity"
quantity1 = gets.to_f + var1
puts quantity1
Note you don't have to specify when a variable is "Float" if you use the decimale separator when you are declaring it. you can see this typing
puts var1.class
it will return Float

How to convert a Base64 encoded string to UUID format

How can I convert a Base64 encoded string to a hex encoded string with dashes(basically to uuid format)?
For example if I have
'FWLalpF2T5mmyxS03Q+hNQ0K'
then how can I convert it to:
1562da96-9176-4f99-a6cb-14b4dd0fa135
I was familiar with unpack but this prompted me to learn the directive as pointed out by cremno.
simplest form:
b64 = 'FWLalpF2T5mmyxS03Q+hNQ0K'
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')
#=> "1562da96-9176-4f99-a6cb-14b4dd0fa135"
b64.unpack("m0")
give us:
#=> ["\x15b\xDA\x96\x91vO\x99\xA6\xCB\x14\xB4\xDD\x0F\xA15\r\n"]
which is an array so we use .first to grab the string and unpack again using the directive to format it in the 8-4-4-4-12 format:
b64.unpack("m0").first.unpack("H8H4H4H4H12")
gives us:
#=> ["1562da96", "9176", "4f99", "a6cb", "14b4dd0fa135"]
an array of strings, so now we just join it with the -:
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')
#=> "1562da96-9176-4f99-a6cb-14b4dd0fa135"
OOPS
The accepted answer has a flaw:
b64 = 'FWLalpF2T5mmyxS03Q+hNQ0K'
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')
# => "1562da96-9176-4f99-a6cb-14b4dd0fa135"
Changing the last char in the b64 string results in the same UUID:
b64 = 'FWLalpF2T5mmyxS03Q+hNQ0L'
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')
# => "1562da96-9176-4f99-a6cb-14b4dd0fa135"
To prevent this, you might want to hash your input (base64 or anything else) to the correct length e.g. with MD5:
require "digest"
b64 = 'FWLalpF2T5mmyxS03Q+hNQ0K'
Digest::MD5.hexdigest(b64).unpack("a8a4a4a4a12").join('-')
# => "df71c785-6552-a977-e0ac-8edb8fd63f6f"
Now the full input is relevant, altering the last char results in a different UUID:
require "digest"
b64 = 'FWLalpF2T5mmyxS03Q+hNQ0L'
Digest::MD5.hexdigest(s).unpack("a8a4a4a4a12").join('-')
# => "2625f170-d05a-f65d-38ff-5d9a7a972382"

Regex Key Value from Text and Brackets

I'm working on trying to parse text from a file into a Hash. Regex just isn't my thing and I am trying to get a better understanding of how to do something like this.
-some-
key1=value1
key2=value2
key3=value3
; comment
-something-
key4=value4
key5=value5
The result should be something like this
some.key1 = value1
some.key2 = value2
some.key3 = value3
something.key4 = value4
something.key5 = value5
I'm working in Ruby and I am able to capture what in between the dashes but the double line breaks, and comments are throwing me off. Currently I have something like this which finds what's in the dashes and puts it in group 1 and then stuffs the next line in group 2, but then stops there.
data = Hash[text.scan(/^\-(.*?)\-\s(.*?)$/m)]
Any help in understanding how this would work is greatly appreciated.
Update: Figured a way to do it with two different Regex's and a loop.
But there has to be a more efficient way, right?
data = Hash.new
Hash[text.scan(/\-(.*?)\-\s([^\r\n]*(?:[\r\n]+(?!\-).*)*)/)].each do |key, value|
data[key] = Hash[value.scan(/(?<=\s|\A)([^\s=]+)\s*=\s*(.*?)(?=(?:\s[^\s=]+=|$))/m)]
end
puts data.inspect
You can do it like this:
text = "-some-
key1=value1
key2=value2
key3=value3
; comment
-something-
key4=value4
key5=value5"
data = Hash[text.scan(/(\w+)=(\w+)/)]
puts data
Output:
{"key1"=>"value1", "key2"=>"value2", "key3"=>"value3", "key4"=>"value4", "key5"=>"value5"}
(\w+) will capture 1 or more alphanumeric symbols on either side of =, and we do not need a multiline mode option here unless you have special characters other than digits, letters and _.

Read one number from file into Variable in Ruby

I want to know how to read a number from a file to a variable. Anyone able to help please?
If the entire file's contents is the number, I'd use File::read to get the contents of the file and String#to_i to convert the resulting string to an integer.
So:
number = File.read('filename.txt').to_i
If your file has a string or variable length of characters that has some numbers in it then you can get all the numbers using regex and assign it to your variable e.g.
file_contents = File.read('filename') # => "a string of character with 23 number and 123 in it"
numbers = file_contents.scan(/\d+/) # => ['23', '123']
To convert the above array of string numbers to integer
numbers.collect! &:to_i # => [23, 123]
Then you can assign these number to any variable you want
number1 = numbers.first
number2 = numbers.last

Resources