Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know Ruby has a bunch of useful operators, like ||=
What other tricky operators does it have?
I haven't found any references for it.
I find that the splat operator is one of the trickiest Ruby operators:
It splits arrays:
a,b,c = *[1,2,3]
Or builds an array:
*a = 1,2,3
It can also be used in case statement:
first = ["one", "two"]
second = ["three", "four"]
case number
when *first
"first"
when *second
"second"
end
It can be used as function argument for varargs:
def stuff *args
args.join('|')
end
As it is used for both (splitting and creating arrays), I always have to check the syntax before using it. It can be used for so many purposes (like converting a hash to an array) that I really find it hard to master.
The ampersand at the end of a method signature will grab and expect a block for you.
def foo(bar, &block)
block.call (bar += 1)
end
The ampersand can also be used in this form to call to_proc and let you call the :address method with a symbol (example is borrowed from elsewhere)
#webs ||= Web.find(:all).index_by &:address
The shortcuts like += and -= are handy.
Not an operator, so much as another shortcut Rails makes possible. This will get you bar when foo is either nil? or false
a = foo || bar
In terms of "operators" I found an (unofficial) thing here for reference: Ruby operators
<=> the "spaceship" or comparison operator
=== the "trequals" or case matching operator
Related
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 2 years ago.
Improve this question
I'm very puzzled with this simple method I have where I'm just trying to puts a character of an array if, when compared with the character of another array, it is different.
This works with the == operator but not with the !=
Maybe it has to do with the each loops but I can't see what the error is. Any ideas?
Thanks
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = []
nw_s.each do |char|
vowels.each do |vowel|
if char != vowel
print char
end
end
end
end
remove_vowels("apple")
Nested each is no ruby way of doing this kind of task. You can write this
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = nw_s.map {|k| k unless vowels.include?(k) }.compact
end
remove_vowels("apple")
One line of code instead seven
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 years ago.
Improve this question
I am the beginner of Ruby.
I get one problem when I read the Ruby code.
There have one function with square-brackets.
How can I get the args from that function?
Here is the Class
class Student
class << self
def count
end
end
end
Here is the function request.
Student.count["Jack"]
Square brackets have no special meaning in Ruby. It is rather a method #[] called on the receiver.
Amongst many others, this method is noticeably declared by Array, Hash and Proc. Because of the parameter passed to #[], which is "Jack" string, it is most likely either Hash or Proc.
That said, it depends on what is returned by Student::count.
Hash example
def count
{"Jack" => 1, "Mary" => 2}
end
count["Jack"]
#⇒ 1
Proc example
def count
->(name) { "Hi, #{name}!" }
end
count["Jack"]
#⇒ "Hi, Jack!"
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
If I defined a method:
def weird_method(first_argument, second_argument)
#code here
end
so this way I can pass arguments like : 1, :digit, 'some', "more"(Fixnum, Symbol, String etc.) , BUT what If I wanted to pass just this: argument1, argument2 , I mean values that have no type and look like local variables but they actually are not. How can I accept them somehow and use them in the method body?
PS: I need it for implementing a small DSL that could do that kind of stuff in the .isntance_eval when blok is passed
Something.with_method do
sum 1, 2 #(I can implement it)
play volleyball #(I can NOT implement it)
swim further #(I can NOT implement it)
eat "a lot" #(I can implement it)
end
EDIT:
Everything could go on the palce of volleyball and further. I am just gave an example. sum, play, swim, eat are methods defined in the Something class.
Symbols exist for exactly the purpose you're talking about here: They're values that just evaluate to themselves. The symbol :volleyball is the symbol :volleyball and that is all it will ever be. It has no other value or meaning.
If you just want it to read differently for aesthetic purposes, your best bet would probably be to define methods that return the appropriate symbol (e.g. def volleyball() :volleyball end). But this seems unidiomatic.
If you really want people to be able to send just about anything that isn't already a method, you could implement a method_missing along the lines of def method_missing(m, *args) m.to_sym end. But I really find this design awkward in most contexts I can think of.
class Something
attr_reader :callstack
def initialize
#callstack = {}
end
def self.with_method &block
self.new.instance_exec &block
end
def method_missing method, *params
params.empty? ? method : callstack[method] = params
end
end
Something.with_method do
sum 1, 2
play volleyball
swim further
eat "a lot"
puts callstack # => {:sum=>[1, 2], :play=>[:volleyball], :swim=>[:further], :eat=>["a lot"]}
end
Does this help?
You must pass objects as method arguments. What functionality are you trying to accomplish by passing arbitrary non-defined names? You could always pass them as a string and then use the string to use the text inside the method.
ex.
def self.methodname(arg1, arg2)
arg1 = arg2
end
Class.methodname("greeting","hello")
would set the variable greeting equal to 'hello'
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 9 years ago.
Improve this question
I have this expression "1=2,3=(4=5,6=7)" and I want to create a Hash out of this - 1 => 2, 3 => (4=5,6=7). I can do this in 2 passes. In first pass, I can transform the (.*) to something like (4;5,6;7) and then in 2nd pass do some split.
Any better solutions?
As long as you don't need to worry about nested parentheses, and
anything inside parentheses are to be treated as a plain string:
str = "1=2,3=(4=5,6=7)"
Hash[str.scan(/([^=,]+)=(\([^\)]+\)|[^=,]+)/)]
# => {"1"=>"2", "3"=>"(4=5,6=7)"}
If you need nested hashes, use a recursive method:
def hashify(str)
arr = str.scan(/([^=,]+)=(\([^\)]+\)|[^=,]+)/).map do |key, val|
if val[0] == '(' && val[-1] == ')'
[key, hashify(val[1..-2])]
else
[key, val]
end
end
Hash[arr]
end
hashify "1=2,3=(4=5,6=7)"
# => {"1"=>"2", "3"=>{"4"=>"5", "6"=>"7"}}
Note that this still doesn't handle nested parentheses properly. You would need a proper parser for that.
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
I often do the following:
#value = #value.some_method
But isn't there a shorter syntax for that in ruby? Some methods offer bang equivalents, but sadly not all...
For iterations one can use:
i += 1
Is that, or something similar, also available for my code snippet above?
There's nothing that does this in a shorter way.
To be fair, it is an unusual pattern, and while not especially rare, would lead to confusion if there was an operator like:
#value .= some_method
How is that even supposed to be parsed when reading?
As the Tin Man points out, in-place operators are really what are best here.
You cannot do that taking the actual variable as the receiver because there is no way to get to the name of the variable. Instead, you need to use the name of the variable like this:
class A
attr_accessor :value
def change_to_do_something name
instance_variable_set(name, "do something")
end
end
a = A.new
a.value = "Hello"
p a.value
# => "Hello"
a.change_to_do_something(:#value)
p a.value
# => "do something"