Splitting array and get desired elements [closed] - ruby

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
If I have this array:
["1","2","3,a","4,b"]
how can I get this array from it?
["1","2","3","4"].

Assuming you have all integers, (If not I guess you get the idea :))
["1","2","3,a","4,b"].collect {|i| i.to_i}

With an array like:
ary = ["1","2","3,a","4,b"]
I'd use:
ary.map{ |s| s[/\A(\d+)/, 1] }
Which results in:
[
[0] "1",
[1] "2",
[2] "3",
[3] "4"
]
It simply finds the numerics at the start of the strings and returns them in a new array.

Try:
["1","2","3,a","4,b"].map(&:to_i)
=> [1, 2, 3, 4]
to get array of strings
["1","2","3,a","4,b"].map(&:to_i).map(&:to_s)
=> ["1", "2", "3", "4"]

This should also works...
array=["1","2","3,a","4,b"]
for i in 0..array.length()-1
if array[i].include?(",")
ab=array[i].split(",")
array[i]=ab[0]
end
end
print array #["1","2","3","4"]

Try this delete option :
irb(main):014:0> a = ["101","2zd","3,a","10,ab"]
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):015:0> count = a.count
irb(main):016:0> for i in 0..count
irb(main):017:1> puts a[i].delete("^0-9")
irb(main):018:1> end
101
2
3
10
UPDATED Code ( Use of Each Loop - Thanks to the Tin Man)
irb(main):005:0> a = ["101","2zd","3,a","10,ab"]
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):006:0> b = []
=> []
irb(main):007:0> a.each do |t|
irb(main):008:1* b << t.delete("^0-9")
irb(main):009:1> end
=> ["101", "2zd", "3,a", "10,ab"]
irb(main):010:0> puts b
101
2
3
10
=> nil

Related

retrieve numbers from a string with regex

I have a string which returns duration in the below format.
"152M0S" or "1H22M32S"
I need to extract hours, minutes and seconds from it as numbers.
I tried like the below with regex
video_duration.scan(/(\d+)?.(\d+)M(\d+)S/)
But it does not return as expected. Anyone has any idea where I am going wrong here.
"1H22M0S".scan(/\d+/)
#=> ["1", "22", "0']
You can use this expression: /((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/.
"1H22M32S".match(/((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/)
#=> #<MatchData "1H22M32S" h:"1" m:"22" s:"32">
"152M0S".match(/((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/)
#=> #<MatchData "152M0S" h:nil m:"152" s:"0">
Question mark after group makes it optional. To access data: $~[:h].
If you want to extract numbers, you could do as :
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i).captures
# => ["1", "22", "32"]
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i)['min']
# => "22"
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i)['hour']
# => "1"
Me, I'd hashify:
def hashify(str)
str.gsub(/\d+[HMS]/).with_object({}) { |s,h| h[s[-1]] = s.to_i }
end
hashify "152M0S" #=> {"M"=>152, "S"=>0}
hashify "1H22M32S" #=> {"H"=>1, "M"=>22, "S"=>32}
hashify "32S22M11H" #=> {"S"=>32, "M"=>22, "H"=>11}
hashify "1S" #=> {"S"=>1}

Breaking it down - simple explanation for regular expressions used in ruby exercise [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 8 years ago.
Improve this question
Problem # 1
In this first problem (line 2) - can someone break it down as to what is happening in terms easy for someone new to Ruby regular expressions to understand?
def encode(string)
string.scan(/(.)(\1*)/).collect do |char, repeat|
[1 + repeat.length, char]
end.join
end
Problem # 2
In this second problem (same answer, but different format to solution) - can someone break it down as to what is happening in terms easy for someone new to Ruby to understand?
def encode(string)
string.split( // ).sort.join.gsub(/(.)\1{2,}/) {|s| s.length.to_s + s[0,1] }
end
It's easy for you to break these down and figure out what they're doing. Simply use IRB, PRY or Sublime Text 2 with the "Seeing is Believing" plugin to look at the results of each operation. I'm using the last one for this:
def encode(string)
string # => "foo"
.scan(/(.)(\1*)/) # => [["f", ""], ["o", "o"]]
.collect { |char, repeat|
[
1 + # => 1, 1 <-- these are the results of two passes through the block
repeat.length, # => 1, 2 <-- these are the results of two passes through the block
char # => "f", "o" <-- these are the results of two passes through the block
] # => [1, "f"], [2, "o"] <-- these are the results of two passes through the block
}.join # => "1f2o"
end
encode('foo') # => "1f2o"
And here's the second piece of code:
def encode(string)
string # => "foobarbaz"
.split( // ) # => ["f", "o", "o", "b", "a", "r", "b", "a", "z"]
.sort # => ["a", "a", "b", "b", "f", "o", "o", "r", "z"]
.join # => "aabbfoorz"
.gsub(/(.)\1{2,}/) {|s|
s.length.to_s +
s[0,1]
} # => "aabbfoorz"
end
encode('foobarbaz') # => "aabbfoorz"

Whether array consists of any value of another array [duplicate]

This question already has answers here:
How can I check if a Ruby array includes one of several values?
(5 answers)
Closed 8 years ago.
I have an array a = ["1","2","3","6","7"] and another array b = ["2","4","7"]. I want to check if any content of b exists in a or not.
You can do
a = ["1","2","3","6","7"]
b = ["2","4","7"]
b.any? { |e| a.include?(e) }
that is so simple:
(a & b).blank?
actually what does it do is, it takes intersection of two array and returns the result then check if the result is blank/empty.
Use & operator of Ruby, it will return an array with intersection values of two arrays, below is an example.
pry(main)> a = ["1","2","3","6","7"]
=> ["1", "2", "3", "6", "7"]
pry(main)> b = ["2","4","7"]
=> ["2", "4", "7"]
pry(main)> a & b
=> ["2", "7"]
pry(main)> (a & b).empty?
=> false
In Rails, you can also use blank?
pry(main)> (a & b).blank?
=> false
Hope the above example helps

How to use multiple .each statements in ruby?

I want to do something like this,
for topic.sections.each do |section| and topic.questions.each do |question|
print section
print question
end
I want both sections and questions simultaneously, the output will be like this:
section 1
question 1
section 2
question 2
I know what i did there is foolish, but, what is the exact way to do this or is this even possible?
Use Enumerable#zip.
For example,
sections = ['a', 'b', 'c']
questions = ['q1', 'q2', 'q3']
sections.zip(questions) { |section, question|
p [section, question]
}
# => ["a", "q1"]
# => ["b", "q2"]
# => ["c", "q3"]
Then do below with the help of Enumerable#zip:
topic.sections.zip(topic.questions) do |section,question|
p section
p question
end

Hash maps in ruby [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Given:
hash = { "value" => 4, "details" => "I am some details"}, {"value" => 5, "details" => "I am new details"}
can I do something like:
hash.each do |key, value|
puts "#{key} is #{value}"
end
to get something like:
{ "value" => 4, "details" => "I am some details"} is {"value" => 5, "details" => "I am new details"} is
If a hash table (map) is not what I want to do this with, what would be? Databases are out of the question. The user should be able to continue to add on to the end with another {} if they need to filling out the same details as what's in the first two.
You've created an array of hashes, which you can do more explicitly as:
hashes = [{:value => "foo"}, {:value => "bar"}]
You can then append with
hashes << {:value => "baz"}
If you're ever wondering what type of variable you're working with, you can do var.class:
hash = { "value" => 4, "details" => "I am some details"}, {"value" => 5, "details" => "I am new details"}
hash.class #=> Array
A Map is a mapping of Distinct Keys to Values; there are Map variations which relax this, but Ruby's Hashmap follows the standard Map ADT.
In this case an Array of two different Hashes (each with a "value" and a "details") is being created.
> x = [1,2] # standard Array literal
=> [1,2]
> x = 1,2 # as in the posted code, no []'s, but ..
=> [1,2] # .. the same: the =, production created the Array here!
So it's not a Hash in hash, but rather an Array (containing two Hash elements) :)
Compare the results with the following and note that b is nil each time:
["one","two","three","four"].each do |a,b|
puts ">" + a + "|" + b
end
This is why it prints "hash1.to_str is hash2.to_str is" as the each iterates over the Array, as discussed above and only the first argument is populated with a meaningful value - one of the hashes.
I don't understand what "databases are out of the question" means in this context. Sounds like you're creating a data store, and so far it looks like you have a numeric ID with a related value.
A hash is a hash; you'd add values to the hash:
h = { "4" => "foo" } # Initial values
h["5"] = "ohai"
h["6"] = "kthxbai"

Resources