Odd string split in ruby? [closed] - ruby

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.

Related

updating array based on symbols Ruby [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 6 years ago.
Improve this question
How does one update the array based on symbols? Like
data = []
string = "Hello"
if( !data.include? string )
count += 1
data.insert(-1, {
label: string,
value: count,
})
else
#logic to change count value if string is encountered again
end
I was thinking of finding the index where the string lies and then delete that to insert another updated values at that index. Is this the right approach?
Just use find to get the match, provided its the only one in the array. You can use select to get multiple matches. After that just update the count
As your example is taken out of context and contains errors, I've taken a liberty to make a more complete example.
data = []
strings = ["Hello", "Bye", "Hello", "Hi"]
strings.each do |string|
hash = data.find{ |h| h[:label] == string }
if hash.nil?
data << {label: string, value: 1}
else
hash[:value] += 1
end
end

How can I produce one whole string from iteration on array of arrays in Ruby [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 9 years ago.
Improve this question
I have array of arrays looking something like this :
arr = [[f,f,f,f,f], [f,f,t,f,f], [f,t,f,t,f]]
and am I outputing it formatted on the console like this:
arr.each {|a| puts a.join.gsub('t','<b></b>').gsub('f','<i></i>')}
and it generates something like this:
<i></i><i></i><i></i><i></i><i></i>
<i></i><i></i><b></b><i></i><i></i>
<i></i><b></b><i></i><b></b><i></i>
but it is only in the output. I am wondering how I can assign it to a string? With the new lines and everything, exactly the way it looks,
a= [["f","f","f","f","f"], ["f","f","t","f","f"], ["f","t","f","t","f"]].map do |arr|
arr.join.gsub(/[ft]/) do |x|
if x =~ /f/
'<i></i>'
elsif x =~ /t/
'<b></b>'
end
end
end.join("\n")
puts a
# >> <i></i><i></i><i></i><i></i><i></i>
# >> <i></i><i></i><b></b><i></i><i></i>
# >> <i></i><b></b><i></i><b></b><i></i>

How can I print out the value of each key in a hash represented by *'s? [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
Here is my code:
class String
def frequency
chars.each_with_object(Hash.new(0)) do |char, h|
h["#{char.upcase}:"] += 1 if char[/[[:alpha:]]/]
end
end
end
I've tried breaking it down in smaller bit's of code, such as using a .times do loop but I couldn't figure it out
for example:
str = "\*"
h["A:"] = count('a').times do
str
end
Are you trying to do something like:
counts = 'aassssvvvvv'.frequency
counts.each{|key,count| puts key + '*'*count}
# A:**
# S:****
# V:*****
Or if you want to change the key you can do:
counts.each{|key,amount| counts[key] = '*'*amount}

Is there a shortcut for assigning some variable with the return value of a method that's used on it in ruby? [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
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"

Tricky operators in Ruby [closed]

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

Resources