Can we override operators in Ruby? [closed] - ruby-on-rails

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 7 years ago.
Improve this question
in a case...such as
(10 + 20) * 10
=> 300
the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication.So does it applies to other operators as well.Can i override other operators such as << !...etc

When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:
10 + 20 * 10 = 300
This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask Ruby to perform the same calculation and you get a very different answer:
> 10 + 20 * 10
=> 210
This is a direct result of operator precedence. Ruby has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, Ruby considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.
Overriding Operator Precedence
The precedence built into Ruby can be overridden by surrounding the lower priority section of an expression with parentheses. For example:
> (10 + 20) * 10
=> 300
In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication.
for more info refer this :
http://rubysnippets.com/2013/01/25/operator-overloading-in-ruby/
Override == operator in Ruby
I hope this makes you clear to understand :)

yes you can,you can do it like this
class String
def << str
self + "*" + str
end
end
puts "str" << "sss"

Related

Started learning Ruby from scratch, why is user_input equivalent to gets.chomp? [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 3 months ago.
Improve this question
I started learning Ruby from scratch, from the preliminary preparation there is a certain knowledge of HTML and CSS. For training I use Code Academy. I have questions and can't always find an answer I can understand I need help understanding the following:
user_input = gets.chomp
user_input.downcase!
Explain why user_input is equivalent to gets.chomp and what that means, thanks in advance!
In Ruby = is used to assign values to variables, as in:
x = 1
y = x
Where y assumes the value of x at the moment that line is executed. This is not to be confused with "equivalence" as in x=y in a mathematical sense where you're establishing some kind of permanent relationship.
In Ruby methods return a value, even if that value is "nothing", or nil. In the case of gets, it returns a String. You can call chomp on that, or any other thing you need to achieve your objective, like chaining on downcase.
On its own gets.chomp will read a line of input, strip off the trailing linefeed character, and then throw the result in the trash. Assigning this to a variable preserves that output.
To understand it, break it down first
Accept user input
Clean the user input (using chomp https://apidock.com/ruby/String/chomp)
Downcase it
user_input = gets # will return the value entered by the user
user_input = user_input.chomp # will remove the trailing \n
# A more idiomatic way to achieve the above steps in a single line
user_input = gets.chomp
# Finally downcase
user_input.downcase!
# By that same principle the entire code can be written in a single line
user_input = gets.chomp.downcase
user_input is equivalent to gets.chomp
Remember, everything in Ruby is an object. So gets returns a String object, so does chomp and so does downcase. Hence with this logic you are essentially calling instance methods on the String class
String.new("hello") == "hello" # true
# "hello".chomp is same as String.new("hello").chomp

How to sum up third elements of string in array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I have the following output:
["1154,1,8.00", "1162,1,8.00", "1161,1,8.00"]
I would like to sum the third element of each item: 8.00 + 8.00 + 8.00
I've tried with .last, .map with no luck.
What is the best way of doing this?
You can do it like this:
["1154,1,8.00", "1162,1,8.00", "1161,1,8.00"].sum { |x| x.split(',').last.to_f }
# output
# => 24.0
arr = ["1154,1,8.00", "1162,1,8.00", "1161,1,8.00"]
rgx = /(?<=,)(?:0|[1-9]\d*)\.\d{2}\z/
arr.sum { |s| s[rgx].to_f }
#=> 24.0
The regular expression can be broken down as follows.
/
(?<=,) # positive lookbehind asserts previous character is ','
(?: # begin non-capture group
0 # match '0'
| # or
[1-9] # match a digit other than '0'
\d* # match zero or more digits
) # end non-capture group
\. # match '.'
\d{2} # match two digits
\z # match end of string
/

Regex with multiple conditions [duplicate]

This question already has an answer here:
Regular expression for password complexity
(1 answer)
Closed 8 years ago.
I'm trying to have the following rules for NSString validation using regular expression:
8 characters minimum length
at least 1 digit
at least 1 uppercase
at least 1 lowercase
I'm only able to do the following to get the first rule like this:
^[a-zA-Z0-9]{8,}$
Which if i understand correctly check for minimum 8 characters length with lower/uppercase and digit
Thank you
Use a lookahead for each assertion:
(?=.*\d)(?=.*[A-Z])(?=.*[a-z])^.{8,}$

How does this regex work? [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 8 years ago.
Improve this question
"Rubymonk Is Pretty Brilliant".match(/ ./, 9)
How is the answer "P" calculated from this regex?
use the match method on the string
passes two arguments, a regular expression and the position in the string to begin the search.
returns the character 'P'
The criteria you posted from the Rubymonk grader answer this succinctly:
passes two arguments, a regular expression and the position in the
string to begin the search
But let's examine that in more detail. match is being passed two arguments:
/ ./, a regular expression
9, the starting position in the string
The regular expression tells us that we're looking for a space () followed by any character (.).
The starting position tells us to start at position 9 (I). So instead of applying that regex against "Rubymonk Is Pretty Brilliant", we're applying it against "Is Pretty Brilliant".
In the string "Is Pretty Brilliant", where is the first place we encounter a space followed by another character? "Is[ P]retty Brilliant", right? Thus match finds a result of P (that's space-P, matching the regex, not just P.)
To see this more clearly and to experiment further with regexes, you can try it in an irb session or in your browser using Rubular.
(Just google for RegEx + ruby, You will find explanation of regex syntax)
/ANYTHING-HERE/
Will look for ANYTHING-HERE in the text.
In Your example its (/ ./,9):
/SPACE DOT/
So it will look for space followed by single character (Dot -> single character).
9 will be "I" from the string. And that is not space, so it will go on 2 characters right. Will find space, and then will find single character "P".
That is the result.

Operator associativity using Scala Parsers

So I've been trying to write a calculator with Scala's parser, and it's been fun, except that I found that operator associativity is backwards, and that when I try to make my grammar left-recursive, even though it's completely unambiguous, I get a stack overflow.
To clarify, if I have a rule like:
def subtract: Parser[Int] = num ~ "-" ~ add { x => x._1._1 - x._2 }
then evaluating 7 - 4 - 3 comes out to be 6 instead of 0.
The way I have actually implemented this is that I am composing a binary tree where operators are non-leaf nodes, and leaf nodes are numbers. The way I evaluate the tree is left child (operator) right child. When constructing the tree for 7 - 4 - 5, what I would like for it to look like is:
-
- 5
7 4 NULL NULL
where - is the root, its children are - and 5, and the second -'s children are 7 and 4.
However, the only tree I can construct easily is
-
7 -
NULL NULL 4 5
which is different, and not what I want.
Basically, the easy parenthesization is 7 - (4 - 5) whereas I want (7 - 4) - 5.
How can I hack this? I feel like I should be able to write a calculator with correct operator precedence regardless. Should I tokenize everything first and then reverse my tokens? Is it ok for me to just flip my tree by taking all left children of right children and making them the right child of the right child's parent and making the parent the left child of the ex-right child? It seems good at a first approximation, but I haven't really thought about it too deeply. I feel like there must just be some case that I'm missing.
My impression is that I can only make an LL parser with the scala parsers. If you know another way, please tell me!
Scala's standard implementation of parser combinators (the Parsers trait) do not support left-recursive grammars. You can, however, use PackratParsers if you need left recursion. That said, if your grammar is a simple arithmetic expression parser, you most definitely do not need left recursion.
Edit
There are ways to use right recursion and still keep left associativity, and if you are keen on that, just look up arithmetic expressions and recursive descent parsers. And, of course, as, I said, you can use PackratParsers, which allow left recursion.
But the easiest way to handle associativity without using PackratParsers is to avoid using recursion. Just use one of the repetition operators to get a List, and then foldLeft or foldRight as required. Simple example:
trait Tree
case class Node(op: String, left: Tree, right: Tree) extends Tree
case class Leaf(value: Int) extends Tree
import scala.util.parsing.combinator.RegexParsers
object P extends RegexParsers {
def expr = term ~ (("+" | "-") ~ term).* ^^ mkTree
def term = "\\d+".r ^^ (_.toInt)
def mkTree(input: Int ~ List[String ~ Int]): Tree = input match {
case first ~ rest => ((Leaf(first): Tree) /: rest)(combine)
}
def combine(acc: Tree, next: String ~ Int) = next match {
case op ~ y => Node(op, acc, Leaf(y))
}
}
You can find other, more complete, examples on the scala-dist repository.
I'm interpreting your question as follows:
If you write rules like def expression = number ~ "-" ~ expression and then evalute on each node of the syntax tree, then you find that in 3 - 5 - 4, the 5 - 4 is computed first, giving 1 as a result, and then 3 - 1 is computed giving 2 as a result.
On the other hand, if you write rules like def expression = expression ~ "-" ~ number, the rules are left-recursive and overflow the stack.
There are three solutions to this problem:
Post-process the abstract syntax tree to convert it from a right-associative tree to a left-associative tree. If you're using actions on the grammar rules to do the computation immediately, this won't work for you.
Define the rule as def expression = repsep(number, "-") and then when evaluating the computation, loop over the parsed numbers (which will appear in a flat list) in whichever direction provides you the associativity you need. You can't use this if more than one kind of operator will appear, since the operator will be thrown away.
Define the rule as def expression = number ~ ( "-" ~ number) *. You'll have an initial number, plus a set of operator-number pairs in a flat list, to process in any direction you want (though left-to-right is probably easier here).
Use PackratParsers as Daniel Sobral suggested. This is probably your best and simplest choice.

Resources