Ruby : Convert String to Float - ruby

I have 3 string variables that I need to add.
a = "5.21", b= "5.22" and c = "5.23".
When I try to add i get a string, I need the numerical value
I have tried the following
a = a.to_f => 5.2
b = b.to_f => 5.2
c = c.to_f => 5.2
sum = a + b + c => 15.6
How do i get output 15.66. please help

Try taking advantage of Ruby's built in Enumerable methods. Try this:
a = "5.21"
b = "5.22"
c = "5.23"
[a, b, c].map(&:to_f).inject(:+)
#=> 15.66

Related

Does Function return multiple value in VBScript? [duplicate]

This question already has answers here:
Return more than one value from a function
(2 answers)
Closed 5 years ago.
We are trying to return multiple values from a single function.
Sub testing()
a = 2
b = 5
temp = func(a, b)
MsgBox temp
End Sub
Function func(a, b)
'we are validating the multiple returns from the function
func = a + b
func = a * b
func = b / a
End Function
VBScript functions return just a single value. If you assign multiple values to the function name as in your example:
func = a + b
func = a * b
func = b / a
only the last value (the result of b / a) will be returned.
To have a function return multiple values you need to wrap the values in a datastructure and return that one datastructure. That could be an array
func = Array((a+b), (a*b), (b/a))
a dictionary
Set d = CreateObject("Scripting.Dictionary")
d.Add "add", (a+b)
d.Add "mul", (a*b)
d.Add "div", (b/a)
Set func = d
a custom object
Class CData
Public add, mul, div
End Class
...
Set c = New CData
c.add = a+b
c.mul = a*b
c.div = b/a
Set func = c
an ArrayList
Set a = CreateObject("System.Collections.ArrayList")
a.Add (a+b)
a.Add (a*b)
a.Add (b/a)
Set func = a
or some other collection.
Note that for returning objects you need to use the Set keyword when assigning the return value of the function:
Set temp = func(a, b)
Yes, with the use of the Array function you can return multiple values from single function.
Function func(a, b)
mul = a * b
div = a / b
add = a + b
sub = a - b
func = Array(mul, div, add, sub)
End Function
then call function like:
val = func(3,4)
print val(0) 'will give multiply of 3*4 = 12
print val(1) 'will give division
print val(2) 'will give addition
print val(3) 'will give subtraction.

Swap two integers in ruby without creating a third

Swap two integers in ruby you can:
a,b = b, a
or:
b ^= (a ^= b)
a ^= b
or so:
a = a + b
b = a - b
a = a - b
Are there more ways to swap two integers without the creation of a third?
Compilation of answers from comments. All are welcome to add their additional answers.
a = b.tap { b = a }
eval("a = #{b}; b = #{a}")
a = b + 0 * (b = a)
Are there more ways to swap two integers without the creation of a third?
temp = a
a = b
b = temp
There are only two Integers in this code, there is no third one created.
Note that several of the examples posted here fail this criterion:
b ^= (a ^= b)
# ^^^^^^ this creates a third integer
a ^= b
a = a + b
# ^^^^^ this creates a third integer
b = a - b
a = a - b

Solve wrong type argument 'cell'

I write in variable 'O' some values using
for i = 1:size(I,1)
for j = 1:size(1,I)
h = i * j;
O{h} = I(i, j) * theta(h);
end
end
I - double, theta - double.
I need to sum()all 'O' values, but when I do it its give me error: sum: wrong type argument 'cell'.
How can I sum() it?
P.s. when I want to see O(), its give me
O =
{
[1,1] = 0.0079764
[1,2] = 0.0035291
[1,3] = 0.0027539
[1,4] = 0.0034392
[1,5] = 0.017066
[1,6] = 0.0082958
[1,7] = 1.4764e-04
[1,8] = 0.0024597
[1,9] = 1.1155e-04
[1,10] = 0.0010342
[1,11] = 0.0039654
[1,12] = 0.0047713
[1,13] = 0.0054305
[1,14] = 3.3794e-04
[1,15] = 0.014323
[1,16] = 0.0026826
[1,17] = 0.013864
[1,18] = 0.0097778
[1,19] = 0.0058029
[1,20] = 0.0020726
[1,21] = 0.0016430
etc...
The exact answer to your question is to use cell2mat
sum (cell2mat (your_cell_o))
However, this is the very wrong way to solve your problem. The thing is that you should not have created a cell array in first place. You should have created a numeric array:
O = zeros (size (I), class (I));
for i = 1:rows (I)
for j = 1:columns (I)
h = i * j;
O(h) = I(i, j) * theta(h);
endfor
endfor
but even this is just really bad and slow. Octave is a language to vectorize operations. Instead, you should have:
h = (1:rows (I))' .* (1:columns (I)); # automatic broadcasting
O = I .* theta (h);
which assumes your function theta behaves properly and if givena matrix will compute the value for each of the element of h and return something of the same size.
If you get an error about wrong sizes, I will guess you have an old version of Octave that does not perform automatic broadcasting. If so, update Octave. If you really can't, then:
h = bsxfun (#times, (1:rows (I))', 1:columns (I));

math calculations in ruby

I have a standard formula for calculating loan amortization schedule.
Here is the formula:
(Px(i/12))/(1-(1+i/12)^-n)
Here is what I have in ruby:
p = BigDecimal('1000.0')
n = BigDecimal('12')
i = BigDecimal('3')
m = (p * (i/12))/(1-(1+i/12) ** -n)
I'm getting a following error: in `**': wrong argument type BigDecimal (expected Fixnum) (TypeError)
I'm having hard time trying to play with Fixnun, Float and BigDecimal in ruby.
n must be an integer per definition if you want to use ** aka BigDecimal#power(n)
PS: I just looked up your formula on wikipedia. Since n is the number of payments, it will be an integer by nature so just use a Fixnum for n - you won't get any troubles :)
Using floats :
>> p = 1000.0
=> 1000.0
>> n = 12.0
=> 12.0
>> i = 3.0
=> 3.0
>> (p*(i/12))/(1-(1+i/12)**-n)
=> 268.447577024146
Using BigDecimal :
>> p = BigDecimal('1000.0')
=> #<BigDecimal:1082c4760,'0.1E4',4(12)>
>> n = BigDecimal('12')
=> #<BigDecimal:1082c14c0,'0.12E2',4(8)>
>> i = BigDecimal('3')
=> #<BigDecimal:1082be2e8,'0.3E1',4(8)>
>> m = (p * (i/12))/(1-(1+i/12) ** -n.to_i)
=> #<BigDecimal:1082b4950,'0.2684475770 2414639639 7495957671 887300036E3',40(48)>
>> m.to_i
=> 268
It seems that the BigDecimal ** only takes a FixNum as the power part...
By putting the .0 at the end of the numbers it makes them all into floats. Works for me.

Strange Ruby String Selection

The string in question (read from a file):
if (true) then
{
_this = createVehicle ["Land_hut10", [6226.8901, 986.091, 4.5776367e-005], [], 0, "CAN_COLLIDE"];
_vehicle_10 = _this;
_this setDir -2.109278;
};
Retrieved from a large list of similar (all same file) strings via the following:
get_stringR(string,"if","};")
And the function code:
def get_stringR(a,b,c)
b = a.index(b)
b ||= 0
c = a.rindex(c)
c ||= b
r = a[b,c]
return r
end
As so far, this works fine, but what I wanted to do is select the array after "createVehicle", the following (I thought) should work.
newstring = get_string(myString,"\[","\];")
Note get_string is the same as get_stringR, except it uses the first occurrence of the pattern both times, rather then the first and last occurrence.
The output should have been: ["Land_hut10", [6226.8901, 986.091, 4.5776367e-005], [], 0, "CAN_COLLIDE"];
Instead it was the below, given via 'puts':
["Land_hut10", [6226.8901, 986.091, 4.5776367e-005], [], 0, "CAN_COLLIDE"];
_vehicle_10 = _this;
_this setDir
Some 40 characters past the point it should have retrieve, which was very strange...
Second note, using both get_string and get_stringR produced the exact same result with the parameters given.
I then decided to add the following to my get_string code:
b = a.index(b)
b ||= 0
c = a.index(c)
c ||= b
if c > 40 then
c -= 40
end
r = a[b,c]
return r
And it works as expected (for every 'block' in the file, even though the strings after that array are not identical in any way), but something obviously isn't right :).
You want r = a[b..c] instead of r = a[b,c].
Difference is: b..c = start from b, go to c, while b,c = start from b and move c characters to the right.
Edit: You don't have to/shouldn't escape the [ and ] either, because you are using strings and not regexen. Also, you have to take the length of the end ("];") into consideration, or you will cut off parts of the end.
def get_stringR(a,b,c)
bp = a.index(b) || 0
cp = a.rindex(c) || bp
r = a[bp..cp + c.size - 1]
return r
end
def get_string(a,b,c)
bp = a.index(b) || 0
cp = a.index(c) || bp
r = a[bp..cp + c.size - 1]
return r
end

Resources