Turn 1.5k to integer ruby on rails - ruby-on-rails

How do I turn "1.5k" into 1500 or "1,766" into "1766" with ruby or rails?
Thanks!

You can do it using ruby without rails.
n = "1,200.5k"
n = n.to_s.gsub(/,+/, '')
n = (n[-1] == 'k' ? n[0...-1].to_f * 1000 : n).to_i
puts n

As for the case "1.5k" you can write a quick method that, if the .to_i() fails, looks for a k as the last character. You can get the last character by doing num_str[-1, 1], where num_str is the original string.
For the other case, I would recommend looking into the money gem. num = Money.parse("1,766").

Related

How to use Rails Web App as ruby script input and output

I'm new to rails and I'm working on this project:
I have done a ruby script which needs an input and that prints some outputs.
Basically it takes the first n decimal digits of PI and then it calculates some stats.
I need to use a rails web app to insert the input, which is a number, and to print the decimal digits and 10 stats rows.
This is the ruby script
require 'bigdecimal/math'
#PI decimals generator
i = 0
j = 0
a_pi = Array.new
print "Insert how many digits do you want to calculate: "
dig_n = gets.chomp.to_i
x = BigMath.PI(dig_n)
a_pi = x.to_s.split('')
begin
a_pi.shift
i += 1
end until i == 3
arr_length = a_pi.length
begin
a_pi.pop
j += 1
end until j == arr_length - dig_n
pi_dec = a_pi.join.to_i
puts pi_dec
I'm using Ruby 2.6 and Rails 6
I think you are thinking about this the wrong way around. What you want is more "a web app/web form that does something with input". Rails might be too much for your use case. If you are not bound to Rails you might want to look into other / lighter web frameworks in ruby like Sinatra or Hanami. This could help: Run ruby script from a HTML form

dealing with many decimal points in ruby on rails

Im currently getting this result for multiplication
(0.01317818 * 0.00014300)
=> 1.88447974e-06
How can I make the returned result
(0.01317818 * 0.00014300)
=> 0.00000188
Across the whole system
To get 8 decimal places:
"%.8f" % (0.01317818 * 0.00014300)
=> 0.00000188
A bit simpler than using big decimal.
You can use bigdecimal. It is a gem.
require 'bigdecimal'
a = BigDecimal.new('0.01317818')
b = BigDecimal.new('0.00014300')
c = a * b

Find all upper/lower/mixed combinations of a string

I need this for a game server using Lua..
I would like to be able to save all combinations of a name
into a string that can then be used with:
if exists (string)
example:
ABC_-123
aBC_-123
AbC_-123
ABc_-123
abC_-123
etc
in the game only numbers, letters and _ - . can be used as names.
(A_B-C, A-B.C, AB_8 ... etc)
I understand the logic I just don't know how to code it:D
0-Lower
1-Upper
then
000
001
etc
You can use recursive generator. The first parameter contains left part of the string generated so far, and the second parameter is the remaining right part of the original string.
function combinations(s1, s2)
if s2:len() > 0 then
local c = s2:sub(1, 1)
local l = c:lower()
local u = c:upper()
if l == u then
combinations(s1 .. c, s2:sub(2))
else
combinations(s1 .. l, s2:sub(2))
combinations(s1 .. u, s2:sub(2))
end
else
print(s1)
end
end
So the function is called in this way.
combinations("", "ABC_-123")
You only have to store intermediate results instead of printing them.
If you are interested only in the exists function then you don't need all combinations.
local stored_string = "ABC_-123"
function exists(tested_string)
return stored_string:lower() == tested_string:lower()
end
You simply compare the stored string and the tested string in case-insensitive way.
It can be easily tested:
assert(exists("abC_-123"))
assert(not exists("abd_-123"))
How to do this?
There's native function in Lua to generate all permutations of a string, but here are a few things that may prove useful.
Substrings
Probably the simplest solution, but also the least flexible. Rather than combinations, you can check if a substring exists within a given string.
if str:find(substr) then
--code
end
If this solves your problem, I highly reccomend it.
Get all permutations
A more expensive, but still a working solution. This accomplishes nearly exactly what you asked.
function GetScrambles(str, tab2)
local tab = {}
for i = 1,#str do
table.insert(tab, str:sub(i, i))
end
local tab2 = tab2 or {}
local scrambles = {}
for i = 0, Count(tab)-1 do
local permutation = ""
local a = Count(tab)
for j = 1, #tab do
tab2[j] = tab[j]
end
for j = #tab, 1, -1 do
a = a / j
b = math.floor((i/a)%j) + 1
permutation = permutation .. tab2[b]
tab2[b] = tab2[j]
end
table.insert(scrambles, permutation)
end
return scrambles
end
What you asked
Basically this would be exactly what you originally asked for. It's the same as the above code, except with every substring of the string.
function GetAllSubstrings(str)
local substrings = {}
for i = 1,#str do
for ii = i,#str do
substrings[#substrings+1]=str:sub(ii)
end
end
return substrings
end
Capitals
You'd basically have to, with every permutation, make every possible combination of capitals with it.
This shouldn't be too difficult, I'm sure you can code it :)
Are you joking?
After this you should probably be wondering. Is all of this really necessary? It seems like a bit much!
The answer to this lies in what you are doing. Do you really need all the combinations of the given characters? I don't think so. You say you need it for case insensitivity in the comments... But did you know you could simply convert it into lower/upper case? It's very simple
local str = "hELlO"
print(str:lower())
print(str:upper())
This is HOW you should store names, otherwise you should leave it case sensitive.
You decide
Now YOU pick what you're going to do. Whichever direction you pick, I wish you the best of luck!

Generating Random Fixed Decimal in Rails

I'm trying to generate random data in my rails application.
But I am having a problem with decimal amount. I get an error
saying bad value for range.
while $start < $max
$donation = Donation.new(member: Member.all.sample, amount: [BigDecimal('5.00')...BigDecimal('200.00')].sample,
date_give: Random.date_between(:today...Date.civil(2010,9,11)).to_date,
donation_reason: ['tithes','offering','undisclosed','building-fund'].sample )
$donation.save
$start +=1
end
If you want a random decimal between two numbers, sample isn't the way to go. Instead, do something like this:
random_value = (200.0 - 5.0) * rand() + 5
Two other suggestions:
1. if you've implemented this, great, but it doesn't look standard Random.date_between(:today...Date.civil(2010,9,11)).to_date
2. $variable means a global variable in Ruby, so you probably don't want that.
UPDATE --- way to really get random date
require 'date'
def random_date_between(first, second)
number_of_days = (first - second).abs
[first, second].min + rand(number_of_days)
end
random_date_between(Date.today, Date.civil(2010,9,11))
=> #<Date: 2012-05-15 ((2456063j,0s,0n),+0s,2299161j)>
random_date_between(Date.today, Date.civil(2010,9,11))
=> #<Date: 2011-04-13 ((2455665j,0s,0n),+0s,2299161j)>

String operation in ruby for credit card number

Working on a rails project where there's an order confirmation string with a credit card number with all but the last four digits starred out. What's the proper way to do a string substitution?
What's the operation to get this
credit_card_number = "1111111111111111"
to this?
credit_card_number = "************1111"
Thanks,
Kenji
Here's a regex approach:
x.gsub!(/.(?=....)/, '*')
Here's an approach using string indexing:
x = '*' * (x.size - 4) + x[-4, 4]
If you're using ActiveMerchant, ActiveMerchant::Billing::CreditCard has an instance method called display_number which does this e.g. XXXX-XXXX-XXXX-4338
If you're not, copy activemerchant:
def last_digits(number)
number.to_s.length <= 4 ? number : number.to_s.slice(-4..-1)
end
def mask(number)
"XXXX-XXXX-XXXX-#{last_digits(number)}"
end
credit_card_number = "1111111111111111"
display_number = mask credit_card_number
You could use Ruby's gsub method and a regular expression to hide some of the numbers in the account number string:
hidenumber = "123-123-1234"
hidenumber.gsub(/(\d{3}-\d{3})/,"xxx-xxx")

Resources