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 9 years ago.
Improve this question
Say that I have three arrays arr1, arr1 and arr3.
arr1 = ["apple", "book", "car", "dog"]
arr2 = ["apple", "book"]
arr3 = ["app", "boo"]
How can I check if arr1 includes: arr2, and arr3 with like wildcards.
You could use Enumerable#grep:
arr3.all? { |item| arr2.grep(/#{item}/)[0] }
#=> true
This matches substrings (e.g. ook), to match only prefixes use /^#{item}/.
Related
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
If I have
footnotes = { "apple" => "is a fruit", "cat" => "is an animal", "car" => "a transport"}
How can I get the index of these?, something like:
footnotes["cat"].index
# => 1
There's no need to first retrieve the keys:
footnotes.find_index { |k,_| k== 'cat' } #=> 1
As to the question of whether hash key-value pairs have an index (since v1.9), I would just point out that the Ruby monks decided to supply us with Enumerable#find_index, which of course means Hash.instance_methods.include?(:find_index) #=> true.
You can do
footnotes.to_a.index {|key,| key == 'cat'}
# => 1
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 have two arrays:
people_keys = ['id', 'name', 'email']
people_values = [[1, 'Tarzan', 'tarzan#jungle.com'],
[2, 'Jane', 'jane#jungle.com' ]]
and I want to make an array of people:
people = []
people_values.each do |person_values|
person = {}
person_values.each_with_index do |person_value, index|
person[people_keys[index]] = person_value
end
people.push( person )
end
This gives me the following result:
people # => [{"id"=>1, "name"=>"Tarzan", "email"=>"tarzan#jungle.com"},
# {"id"=>2, "name"=>"Jane", "email"=>"jane#jungle.com" }]
I want to make id, name and email symbols instead of strings,
so I came up with the following:
I replaced
person[people_keys[index]] = person_value
with
person[:"#{people_keys[index]}"] = person_value
This gives me the following result:
people # => [{:id=>1, :name=>"Tarzan", :email=>"tarzan#jungle.com"},
# {:id=>2, :name=>"Jane", :email=>"jane#jungle.com" }]
This works just fine but seems like it could be done better/cleaner,
but I am unable to find a better solution.
I'd like to know if there is in fact a better solution for this problem.
Ruby's String class has a to_sym method:
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist.
You could do something like this:
people_values.map { |person| people_keys.map(&:to_sym).zip(person).to_h }
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Improve this question
Im trying to write a standalone method named count_lines that returns the number of lines in an input string.
If i run this test code it should produce the output shown:
s = %W/This
is
a
test./
print "Number of lines: ", count_lines(s), "\n"
# Output:
Number of lines: 4
I am fairly new to Ruby and I am trying to figure out if this pseudocode of the actual output or not. Please help me!!
I would assume count_lines is a method that counts the number of elements in a an array, you can count the number of elements using of the several methods ruby provides look up the Array Documentation for this, and %W is a one of ruby niceties which allows you create an array of strings, e.g:
arr = %W{a b c}
arr # => ["a", "b", "c"]
It takes almost any special character as a delimiter e.g using . as a delimeter
arr = %W.a b c.
arr # => ["a", "b", "c"]
So in your snippet from the question / is delimiter used, so s would evaluate as below:
s = %W/This
is
a
test./
s # => ["This", "is", "a", "test."]
The above explains why the below works as it does
def count_lines(arr)
arr.size
end
s = %W/This
is
a
test./
print "Number of lines: ", count_lines(s), "\n"
# >> Number of lines: 4
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 9 years ago.
Improve this question
By a is a json subset of b, I mean
For object, b has all the key-value pairs as in a.
For array, b has the same size as a, the order doesn't matter though
{"one":1}.should be_subset_json({"one":1,"two":2})
[{"one":1}].should_NOT be_subset_json([{"one":1},{"two":2}])
[{"two":2},{"one":1}].should be_subset_json([{"one":1},{"two":2}])
[{"id":1},{"id":2}].should be_subset_json([{"id":2, "name":"b"},{"id":1,"name":"a"}])
Just implementing your spec there seems to work.
require 'json'
def diff_structure(a, b)
case a
when Array
a.map(&:hash).sort == b.map(&:hash).sort
when Hash
a.all? {|k, v| diff_structure(v, b[k]) }
else
a == b
end
end
RSpec::Matchers.define :be_subset_json do |expected|
match do |actual|
diff_structure JSON.parse(actual), JSON.parse(expected)
end
end
describe "Data structure subsets" do
specify { '{"one":1}'.should be_subset_json('{"one":1,"two":2}') }
specify { '[{"one":1}]'.should_not be_subset_json('[{"one":1},{"two":2}]') }
specify { '[{"two":2},{"one":1}]'.should be_subset_json('[{"one":1},{"two":2}]') }
specify { '{"a":{"one":1}}'.should be_subset_json('{"a":{"one":1,"two":2}}') }
end
# Data structure subsets
# should be subset json "{\"one\":1,\"two\":2}"
# should not be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "{\"a\":{\"one\":1,\"two\":2}}"
# Finished in 0.00172 seconds
# 4 examples, 0 failures
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 9 years ago.
Improve this question
for example:
input: 15
output:
15 = 1+2+3+4+5
15 = 4+5+6
15 = 7+8
input: 4
output: cannot split
Here's one way:
def natural_numerals(value)
results = []
(1..value-1).each {|i| (i..value-1).each {|j| results << (i..j).to_a.join("+") if (i+j)*(j-i+1)/2 == value}}
if results.empty? then nil else results end
end
output1 = natural_numerals(15)
output2 = natural_numerals(4)
puts output1.inspect #=> ["1+2+3+4+5", "4+5+6", "7+8"]
puts output2.inspect #=> nil