I have a string like this (YYYYMMDD):
20120225
And I want to have a string like this (MM/DD/YYYY):
02/25/2012
What's a good way of doing this in Ruby? I have thought about converting the first string to a Date, and then change the format. Or just treating the string and getting the parts I want and build the new string.
Parsing it then formatting it is the best solution:
Date.parse("20120225").strftime("%m/%d/%Y") #=> "02/25/2012"
strptime parses the string representation of date with the specified template and creates a date object.
Date.strptime('20120225', '%Y%m%d').strftime("%m/%d/%Y") #=> "02/25/2012"
Just for fun how about:
'20120225'.unpack('A4A2A2').rotate.join('/')
It's possible with regular expressions:
s1 = '20120225'
s2 = "$2/$3/$1" if s1 =~ /(\d{4})(\d{2})(\d{2})/
Or if you're sure of the format of your string and have performance issues, I think the best solution is
s2 = s1[4..5] + '/' + s1[6..7] + '/' + s1[0..3]
But if you have no performance needs, I think the solution of Andrew Marshall is better because it checks the date validity.
Related
I have a string that represents a date:
"12.27.1995"
I need to swap the month and the day to get:
"27.12.1995"
I did:
date = "12.27.1995"
month = date[0]+date[1]
day = date[3]+date[4]
date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]
It works good, but looks to bad for me. Is it possible to make it more reliable using less code?
Since your string represents a date, you might want to use a Date object, with strptime to parse the original string and strftime to output it in the desired format:
require 'date'
date = Date.strptime("12.27.1995", "%m.%d.%Y")
puts date.strftime("%d.%m.%Y")
# 27.12.1995
Yes. Perhaps like this:
date = "12.27.1995"
m, d, y = date.split(".")
date = [d, m, y].join(".")
While the answer by #sawa is perfectly valid and should be used here, I would show some technic which is wrong and should not be used here, but might be helpful for anybody to swap two fixed parts of the string:
"12.27.1995".tap { |s| s[0..1], s[3..4] = s[3..4], s[0..1] }
#⇒ "27.12.1995"
Not elegant, but a way using regex captures:
/(\d{1,2})\.(\d{1,2})\.(\d{4})/.match "12.27.1995"
[$2, $1, $3].join('.') #=> "27.12.1995"
I have ugly string that looks like this:
"\"New\"=>\"0\""
Which will be the best way to converting it into hash object?
Problem with "\"New\"=>\"0\"" is it does not look like a Hash. So first step should be to manipulate it to look like a Hash:
"{" + a + "}"
# => "{\"New\"=>\"0\"}"
Now once you have a hash looking string you can convert it into Hash like this:
eval "{" + a + "}"
# => {"New"=>"0"}
However there is still one issue, eval is not safe and inadvisable to use. So lets manipulate the string further to make it look json-like and use JSON.parse:
require `json`
JSON.parse ("{" + a + "}").gsub("=>",":")
# => {"New"=>"0"}
How about JSON.parse(string.gsub("=>", ":"))
You can use regex to pull out the key and value. Then create Hash directly
Hash[*"\"New\"=>\"0\"".scan(/".*?"/)]
Hard to nail down the best way if you can't tell us exactly the general format of those strings. You may not even need the regex. eg
Hash[*"\"New\"=>\"0\"".split('"').values_at(1,3)]
Also works for "\"Rocket\"=>\"=>\""
What is the best way to get '51', out of the following string in ruby :
"<https://api.example.com/users/lgs/api?page=2>; rel=\"next\", <https://api.example.com/users/lgs/api?page=51>; rel=\"last\""
Thanks in advance
Luca
If you know there're only two numbers in that string then this is enough:
str = '"<https://api.example.com/users/lgs/api?page=2>; rel=\"next\", <https://api.example.com/users/lgs/api?page=51>; rel=\"last\""'
p str.scan(/\d+/).last #=> "51"
If not then provide more detail to make the regex more precise. Also you can add to_i if you need the answer as a number.
You can use regexp in this way:
res = str.match /.page=(\d+)./
in this way you are "capturing all the digits between "(" and ")" (in the last token), and you result will be store in
res.captures.first
(or simply in $1 variable)
Looking for some Regex help in Ruby.
I have a string that is formated as so:
YYYY-MM-DD-title-of-post.markdown
I'm looking to use gsub or sub to remove the YYYY-MM-DD portion of the string and do further processing to it.
I would like a Regular Expression to remove the date from the string. The date will never be in a different format.
Thanks for the help!
This should do the trick:
new_title = old_title.gsub('\d{4}-\d{2}-\d{2}','')
If you are confident that the date will ALWAYS be in the format YYYY-MM-DD and will ALWAYS appear at the beginning of the string than the following regex will work:
my_string = "YYYY-MM-DD-title-of-post.markdown"
date = my_string.match(/^(\d{4}-\d{2}-\d{2})-.*/)[1]
I want to extract the quoted substrings from inside a string. This is an example:
string = 'aaaa' + string_var_x + 'bbbb' + string_var_y
The output after parsing should be:
["'aaaa'", "'bbbb'"]
The initial solution was to string.scan /'\w'/ which is almost ok.
Still I can't get it working on more complex string, as it's implied that inside '...' there can be any kind of characters (including numbers, and !##$%^&*() whatever).
Any ideas?
I wonder if there's some way to make /'.*'/ working, but make it less greedy?
Lazy should fix this:
/'.*?'/
Another possibility is to use this:
/'[^']*'/
An alternate way to do it is:
>> %{string = 'aaaa' + string_var_x + 'bbbb' + string_var_y}.scan(/'[^'].+?'/)
#=> ["'aaaa'", "'bbbb'"]
String.scan gets overlooked a lot.