This might be a silly question. But, I am a newb... How can you have a multi-line code in the interactive ruby shell? It seems like you can only have one long line. Pressing enter runs the code. Is there anyway I can skip down to the next line without running the code? Again, sorry if this is a dumb question. Thanks.
This is an example:
2.1.2 :053 > a = 1
=> 1
2.1.2 :054 > b = 2
=> 2
2.1.2 :055 > a + b
=> 3
2.1.2 :056 > if a > b #The code ‘if ..." starts the definition of the conditional statement.
2.1.2 :057?> puts "false"
2.1.2 :058?> else
2.1.2 :059 > puts "true"
2.1.2 :060?> end #The "end" tells Ruby we’re done the conditional statement.
"true" # output
=> nil # returned value
IRB can tell us the result of the last expression it evaluated.
You can get more useful information from here(https://www.ruby-lang.org/en/documentation/quickstart/).
One quick way to do this is to wrap the code in if true. Code will run when you close the if block.
if true
User.where('foo > 1')
.map { |u| u.username }
end
If you are talking about entering a multi-line function, IRB won't register it until you enter the final end statement.
If you are talking about a lot of individual expressions such as
x = 1
y = 2
z = x + y
It's OK if IRB executes each as you enter it. The end result will be the same (for time-insensitive code of course). If you still want a sequence of expressions executed as fast as possible, you can simply define them inside of a function, and then run that function at the end.
def f()
x = 1
y = 2
z = x + y
end
f()
Related
Many times in administering rails web applications, I find myself developing methods that I want to call from rails console since they are designed to solve specific problems and so they usually don't deserve a place in the administrative area.
Suppose that i've a method that returns an array of data.
I want to perform some operation on each one.
1.9.3 > x = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
1.9.3 > x.each() do |x|; puts x; end
1
2
3
4
5
=> [1, 2, 3, 4, 5]
The last line is the one that i want to skip.
Thats because actually the array is of Model objects having many fields and the elements are several tens.
So the unneeded repetition of what my input has been, has the effect of scrolling the console by thousand of lines with the result of hiding the log of my operation.
I tried with for - in loop hoping that it didn't return the value, but it do so too.
This is sort of trivial issue, but it's seriously impairing my rails-c-based administrative approach.
Is there a way to overcome it?
Like this?:
$> rails c
=> Loading development environment (Rails 4.1.0)
=> [1,2,3,4].each { |x| puts x };nil
#> 1
#> 2
#> 3
#> 4
#> nil
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").
In Ruby-on-rails, I am receiving input from a call to a XL macro(currently hard coded), which places a mathematical expression in the spreadsheet. If I call the macro I will receive a worksheet with an expression like this in one of the cells
x + ( 3 / 12)
In the R-O-R application I wish to take this expression and evaluate for different values of x.
row.each do |row|
y = row
end
I want to find the value of y for say example x = 2 ? Should I receive this expression as a literal ?
There is no built-in function to do this securely. You need a math parser and evaluator. You can write one yourself or you could use an existing one like Dentaku.
eval and gsub will get you most of the way there. Fire up irb:
(533)⚡️ irb
2.1.2 :001 > exp = 'x + (3 / 12)'
=> "x + (3 / 12)"
2.1.2 :002 > eval(exp.gsub(/x/, '25'))
=> 25
2.1.2 :003 > exp = 'x + (4.0 / 25.0) + 4'
=> "x + (4.0 / 25.0) + 4"
2.1.2 :004 > eval(exp.gsub(/x/, '25'))
=> 29.16
Notice the result of command 002. Ruby is assuming the 3 / 12 is integer math, so the result will be an integer, which is 0 in this case. In 003 floating point math occurs because the numbers are decimals. This aspect may be an issue you need to tackle more creatively, or just make sure your expressions conform to the type of math you need to occur.
Be aware of the security concerns with eval, you're executing Ruby code in there, so mean people may put mean things in there to try and execute it.
Why not write a one line function, as following:
def foo(x) x + (3 / 12) end
Now you can use this to calculate any value of x, for x = 2, you can do: foo(2) or foo 2.
I'm stuck on a homework problem, and found a solution by looking at someone's work. Problem is I don't understand it. Here's the code
ordering, #title_header = {:order => :title}, 'hilite'
What is happening to 'ordering' in this case? I tried googling to see if that's a method, but couldn't find anything.
What you're seeing is actually list expansion. Ruby can do the following:
a, b = 1, 2
This is essentially the same as:
a = 1
b = 2
I'll leave the rest for you to figure out.
This is "parallel assignment".
Parallel assignment in Ruby is what happens when there is more than 1 lvalue (i.e., value on the left-hand side of the equals sign) and/or more than 1 rvalue (value on the right-hand side of the equals sign).
To understand parallel assignment, there are various cases to consider.
Case #1: One value on the left, multiple values on the right
The first, simplest case is when there is 1 lvalue and multiple rvalues. For example:
> a = 1, 2
> a
=> [1, 2]
All that's happening is the right-hand comma-separated list of values is converted into an array and assigned to the left-hand variable.
Case #2: Multiple values on the left, the same number of values on the right
The second case is when there are the same number of lvalues and rvalues. For example:
> a,b = 'foo', 'bar'
> a
=> "foo"
> b
=> "bar"
This is also pretty straightforward -- you simply evaluate each item on the right hand, then assign it to its corresponding variable on the left-hand side, in order.
Case #3: Multiple values on the left, one value on the right -- but it's an array
The third case is when the rvalue is an array, and that array's elements are distributed (or "expanded") among multiple lvalues. For example:
> a, b = ['foo', 'bar']
> a
=> "foo"
> b
=> "bar"
This is effectively the same as case #2, above, except in this case explicitly employing array syntax.
Case #4: More values on the left than on the right
The fourth case is when there are multiple values on both sides, and there are more lvalues than rvalues. For example:
> a, b, c = 'foo', 'bar' # Note only 2 values on the right
> a
=> 'foo'
> b
=> 'bar'
> c
=> nil
As you can see, Ruby did the best it could to distribute the values, but ran out of them and was forced to assign nil to the last variable on the left.
Case #5: More values on the right than on the left
The fifth case is when there are multiple values on both sides, and there are fewer lvalues than rvalues. For example:
> a, b = 'foo', 'bar', 'baz' # Note only 2 values on the left
> a
=> 'foo'
> b
=> 'bar'
Again, Ruby did the best it could to distribute the values, but had too many to parcel out, and was forced to send the right-most value ("baz") into the ether.
Case #6+: Splatting
Note in the case above, we lost the last value. However it is actually possible to capture any such excess values and gather them into an array, using a related operator called the "splat" operator (which consists of an asterisk in front of the variable, as in *my_var). You can do a number of useful things with this "splat" operator, but so as not to overload this answer too much, it's probably better to go elsewhere to look at examples of it in action. E.g., this blog post lists several variant uses.
Note: Swapping without a temp variable
One nice aspect of this parallel assignment facility is that you can swap values conveniently.
To swap values without parallel assignment, you might write something like this:
> a = 'foo'
> b = 'bar'
> temp = a # Introduce a temp variable
> a = b
> b = temp
> a
=> "bar"
> b
=> "foo"
But with parallel assignment, you can simply rely on Ruby to implicitly handle the swapping for you:
> a = 'foo'
> b = 'bar'
> b, a = a, b
> a
=> "bar"
> b
=> "foo"
for i in (0..5)
if(i==0)
i=4
end
puts i
end
In the above program I excepted the output as - 4 5
But instead it is - 4 1 2 3 4 5
So I conclude that loop variable isnt changing. How can change it? Can anyone tell me?
Actually, In my program I need to save the current state of loop and retrive later so that on the next start program resumes from the same point where it was left.
The only way you'll be able to modify the loop variable is to use a while loop:
x = (2..7).to_a
i = 0
while (i < x.length)
i = 4 if i == 0
puts x[i]
i = i + 1
end
Output:
6
7
In a for loop, as you've discovered, you can modify the loop variable and that value will hold for that iteration of the loop. On the next iteration, it will retrieve the next element from the range you specified so your modified value will essentially be overwritten.
There is no way to do that without a hack. The next best thing would be to use next.
x = (0..5).to_a
for i in (0..5)
if(i < 4)
next
end
puts x[i]
end
produces:
4
5
I am not sure how your code relates to the problem you are later mentioning. It looks to me that all you need to do is:
start_pos = load_start_pos || 0 # if not available for load, assume zero
(start_pos..end_pos).each do |i|
if need_to_exit?
save_start_pos i # save for later
break # exit the loop
end
end