I need to convert a mixed number to float type, for eg: 1 1/2 to 1.5.
Is there any built in method in ruby to achieve the same?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could split into pieces, convert the pieces to Rationals, sum the Rationals, and convert the result to a Float:
If you know that the string will always have two parts then you could handle the pieces separately:
If you’re not sure how many parts there will be (i.e.
'1','3/2','11 23/42', … are all possible) then the first one should work in all cases.Kernel#Rational will raise an ArgumentError if it can’t parse the string so you might want to wrap the whole thing in a
begin/exceptblock to deal with errors.