Evaluating a piece of string as code in Ruby [closed] - ruby

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Take a string like "4 / 10 + 5 x 3"
how would you parse the string in Ruby and evaluate the math?
Note: Hopefully, the solution doesn't involve regex if possible

You can use eval to evaluate a string as Ruby code.
eval(string [, binding [, filename [,lineno]]])
Evaluates the Ruby expression(s) in string. If binding is given, which
must be a Binding object, the evaluation is performed in its context.
If the optional filename and lineno parameters are present, they will
be used when reporting syntax errors.
In your case
string = '4 / 10 + 5 * 3'
eval(string)
Keep in mind that the string you posted is not valid Ruby code. In fact, x is invalid, the correct operator is *.

str = "4 / 10 + 5 x 3"
eval(str.tr("x","*"))
If you want to keep the x you can translate it using tr.
eval can run anything, so don't try this with user input.

str = "4 / 10 + 5 x 3"
result = eval(str)

Your current code will throw a Syntax error since you're trying to multiply using the character x.
You should use * operator.
After that it's simple by using eval(). But normally this should be refrained from.
result = eval("4 / 10 + 5 * 3")
For math parsing I would look into this gem, haven't tried it myself but seems better than raw eval.

Related

Ruby, string with a mathematical calculation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
In this challenge you must implement the method code that receives a string with a mathematical calculation and returns the value that ? must have for the account result to be correct.
'100 + ? + 3 = 108'
How to find ? value in ruby.
can someone explain how to solve?
Computers are really dumb and need to be told what to do.
Try solving the problem yourself by hand and when it's very clear for you how to solve it, try to implement it.
I'll give you a start
Validate if the input is empty or nil
Split the input into its parts '100 + ? + 3 = 108' => ["100", "+", "?", "+", "3", "=", "108"] (you can put them in an array)
Check if each part is a number, an operator or a ?
If it's a number, transform it from string to number
if It's an operator check which one, +, -, etc. and then act on it taking left and right side of the operator
etc. etc
You'll notice it's not trivial, but eventually each one of those paragraphs can be translated into specific ruby code.
Give it a try and ask again when you get stuck.

Ruby syntax error with declarative concept of using variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to use the reactive programming concept in ruby, I have create two block of code:
1 Imperative
a = 5, b = 2
c = a + b
print c #=> 7
a = 2
print c #=> 7
2 Declarative
a := 5, b := 2
c := a + b
print c #=> 7
a := 2
print c #=> 4
However second example doesn't work for me and give the below error:
d.rb:1: syntax error, unexpected '=', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
a := 5, b := 2
^
Please anyone help me to find out the error in the code. Any suggestion will be highly appreciated.
I know the second one is pseudo code but one thing surprise me that top score person make it off topic? The second code can also be executed using Reactive Library and top score programmer don't aware about it.
The := is not valid Ruby.
The error message is because symbols are represented by leading colons so :example is a symbol (compare to "example" which is a string).
So encountering : Ruby expects a valid beginning character for a symbol, which would be any of...
#$_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
Middle characters can be...
_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
And the last character can be...
!_=?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
So = is never a valid symbol character.
The article you reference is showing pseudo-code not actual Ruby.

Issue with my Ruby Assignment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am new to learn Ruby, I got an assignment from my teacher which I am trying to understand.
Here is the question. Consider the following code:
ary = Array.new(7, "--day")
ary[2] = "Tuesday"
ary[4] = "Thursday"
ary[7] = "Sunday"
ary[-1] = "Saturday"
puts ary[7]
puts ary[-4]
puts ary[-6, 2]
puts ary[2] = ary[7][-3,3]
puts ary.length
Why does this code produce 6 lines of output? Where did the extra line come from?
What is the value of ary[2] at the end?
Why is the length (or size) of the array different than when we constructed it?
I won't answer these questions directly, since it sounds like it's a homework assignment, but I will try to point you in the right direction.
Take a look at the documentation for Ruby's Array#[]. More specifically, take a look at which usages in your example code match the usages in the examples, and you might get a better idea of what's happening. Keep in mind that with Ruby, you can index from the end of your array by using negative index numbers.
Open up irb in the terminal and run the first 5 lines (all the ary[]= lines). Then run each of the puts lines individually and see what the output is. Keep in mind that lines with => something are the return values, not what is being printed.
Take a look at String#[], and try out the different parts of line 9 individually. For example, see what ary[7] does. Then see what ary[7][-3, 3] does. See what happens if you do "Any Random String"[a_number, another_number].
After you first create the array, check ary.length. Then run each of the following lines, checking ary.length after each subsequent assignment.
Don't get discouraged, and don't listen to people telling you to give up. This stuff can be confusing when you first start out, but getting familiar with where to find documentation, how to use the command line tools, and how to experiment will make it much easier to explore and discover what your code is doing, when, and why.
If you ever need to try and figure out what is going on in your code, just open up irb in your terminal and start playing around with it, and you should be able to answer most of your questions through experimentation.

< > inside a Ruby String [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I was reading something else posted by a user on here explaining how yield statements work in Ruby. Part of the code he was using was :
print_list( [1,2,3], 23 ) { |n| "<#{n}>"}
what do the < > mean inside the string? It's such a simple question but I haven't been able to find out the answer to it.
In a string literal neither < nor > have any implied meaning - although such might have meaning in the output or use of the resulting string.
Only escape sequences and # (in interpolated literals) have intrinsic meaning.
These characters are just a part of string.
And any character which lies inside #{ } will be evaluated, which is also referred to Interpolation

Swap two strings 2 by 2 in ruby [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I've go a string made in this way.
"AABBCCDD....." grouped by 4 with variable lenght.
I need a method that swap that 2 by two the chars in this string
def swap2_by_2( string )
???
end
If the input is AABBCCDD the output will be BBAADDCC
Thanks, i'm very noob in ruby.
Edit: my mistake, a more comprhensive example may be.. Input: ABCDEFGH -> CDABGHEF
It is not clear what the OP is trying to do, but if it is to flip the first and the second characters with the third and fourth characters for every four characters, then the example that the OP showed is highly misleading and inappropriate (It should have been "ABCD..." instead of "AABB..."). In that case, a solution would be:
string.gsub(/(..)(..)/, '\2\1')
Thinking about your question, an interpreting the "ABCDEF", I am sure, that you are looking for pack / unpack in Ruby: I found a good page here How to change bit order in Ruby
And here are two a non-regexp versions:
p 'AABBCCDD'.chars
.each_slice(2)
.each_slice(2)
.map(&:reverse)
.join
#=> "BBAADDCC"
# or
'AABBCCDD'.chars
.each_slice(4)
.map{|x| x.rotate(2)}
.join

Resources