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
Is there a better way to do this?
value = 10
train = []
storage = 12
another_var = 'apple'
def first_function(value, train, storage, another_var)
second_function(train, storage)
third_function(train, storage, another_var)
forth_function(value, another_var)
end
def third_function(train, storage, another_var)
puts 'x'
end
def second_function(train, storage)
puts 'x'
end
def forth_function(value, another_var)
puts 'x'
end
Is this the proper way to do this? Taking the values along for the ride? I'm working my way through LRTHW and I'm trying to build a game. The problem I am running into is that I have a for loop that represents turns and that acts as the game driver. Inside of that for loop it calls functions that then call more functions. Unless I load all the variables into the first function and then pass them down the chain it breaks. It's sort of neat that it blocks you from accessing variables outside of the very narrow scope, but is there a way I can override this?
You may want to use instance variables to keep them in scope without having to pass them as parameters every time.
#value = 10
#train = []
#storage = 12
#another_var = 'apple'
def first_function
second_function
third_function
fourth_function
end
def third_function
puts #another_var
end
def second_function
puts #value + #storage
end
def fourth_function
puts #train
end
I believe what you want is to be able to do all combinations of optional parameters.
Try this:
def myfunction(options={})
options = {:value => 10, :train => [], :storage => 12, :another_var => 'apple'}.merge(options)
puts options[:value]
puts options[:train]
puts options[:storage]
puts options[:another_var]
end
Example usage:
irb(main):013:0> myfunction({})
10
12
apple
=> nil
irb(main):014:0> myfunction({:value => 11, :storage => 23})
11
23
apple
=> nil
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 2 years ago.
Improve this question
class RecipePuppyAPI1
URL = "http://www.recipepuppy.com/api/"
def get_recipes
uri = URI.parse(URL)
response = Net::HTTP.get_response(uri)
JSON.parse(response.body)
end
def recipe_titles(json)
recipes = []
json.collect do |recipe|
recipes << recipe["title"]
end
end
end
recipes = RecipePuppyAPI1.new.get_recipes
puts ap recipes.uniq
Your recipe_titles method doesn't return the right thing. collect is used to map 1:1 an input array to an output array, and the output of each iteration is the result.
It looks like you're confusing each, an iterator, with collect, which is a transform operation. You're also declaring an array which isn't used properly, as normally that'd be your return value.
To fix it, remove the temporary variable, strip it down to this:
def recipe_titles(json)
json.collect do |recipe|
recipe["title"]
end
end
Or more generically:
def recipe_fields(json, field)
json.collect do |recipe|
recipe[field]
end
end
Where you can call it like:
recipe_fields(json, 'title')
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 3 years ago.
Improve this question
My Ruby question is in a given array of non-empty strings, create and return a hash as follows: for each string add its first character as a key with its last character as a value in defn method
def pairs1(arry)
arry = [ "code", "bug"]
final_hash = {}
pairs1.each do |var|
final_hash[] = puts var[0] puts var[-1]
final_hash[var[0]] = var[-1]
end
puts final_hash
The error I got is :
syntax error, unexpected tIDENTIFIER, expecting keyword_end
...final_hash[] = puts var[0] puts var[-1]
... ^~
Looking at your code:
def pairs1(arry)
arry = [ "code", "bug"]
final_hash = {}
pairs1.each do |var|
final_hash[] = puts var[0] puts var[-1]
final_hash[var[0]] = var[-1]
end
puts final_hash
A few things are a bit off. You should remove the array initialization (arry = [...]) because you're passing in a array through the parameters of the method already. If you keep it like this, passing a parameter won't have any effect on the method. Also this line final_hash[] = puts var[0] puts var[-1] doesn't do anything (aside from raising an error), so you can remove it too. You also want to call the #each methon on the array, calling it on the method itself doesn't make much sense here. If you also add an end to the end of the method you get a working version of your method:
def pairs1(arry)
final_hash = {}
arry.each do |var|
final_hash[var[0]] = var[-1]
end
puts final_hash
end
Keep in mind, this method currently doesn't return the value of final_hash, it just prints the value to the console and returns nil. If you want to change that just remove the puts from the last line.
You can also do something like this:
arry = [ "code", "bug"]
def pairs1(arry)
arry.each_with_object({}) { |element,hash| hash[element[0]] = element[-1] }
end
pairs1(arry)
# => {"c"=>"e", "b"=>"g"}
You forgot to add end to the close defining of the method.
You can use inject method too. And for readability I prefer chars.first and chars.last
arry = ['code', 'bug']
final_hash = arry.inject({}) do |memo, val|
memo[val.chars.first] = val[val.chars.last]
memo
end
p final_hash
{"c"=>"e", "b"=>"g"}
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 9 years ago.
Improve this question
I was hoping something like this would work:
while i < 3 do
puts i
#b[i] = Benchmark.new
i += 1
#a += 1
end
puts "Here is a #{#a}"
puts #b0.inspect
puts #b1.inspect
puts #b2.inspect
Sadly, it doesn't work at all. []= is regarded as an unrecognised method!
You can also use instance_variable_set
3.times{|i| instance_variable_set "#x#{i}", i }
#x1 # => 1
#x2 # => 2
Though for this particular task you should use arrays, it's a rookie mistake to use lots of variables instead of lists.
benchmarks = []
n.times { benchmarks << Benchmark.new } # or benchmarks = (0..n).map { Benchmark.new }
benchmarks.each do |bm|
# do stuff
end
This is clearly a job for an array, not for many instance variables.
benchmarks = number.times.map { Benchmark.new }
puts "Here is a #{number}"
benchmarks.each { |b| puts b.inspect }
Answered my own question! The eval method is the answer:
puts "Welcome to Benchmark 1.0! How many benchmarks do you wish to perform? (We recommend three)"
number = gets.chomp.to_i
#a = 0
i = 0
while i < number do
puts i
eval("#b#{i} = Benchmark.new")
i += 1
#a += 1
end
puts "Here is a #{#a}"
puts #b0.inspect
puts #b1.inspect
puts #b2.inspect
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'm using Solr to search for a list of companies. when I try to filter
Works
companies = []
current_user.cached_company.cached_companies.each do |company|
companies << company.id
end
Doesn't Work
companies = []
companies << current_user.cached_company.cached_companies.map(&:id)
When I call
#search = Company.search do
with :id, companies
end
#companies = #search
It works with the first example but not the second.
However, this works just fine
#search = Company.search do
with :id, current_user.cached_company.cached_companies.map(&:id)
end
#companies = #search
I know that I'm missing something simple here. I know it doesn't have to do with the caching, but cannot wrap my head around what's going on.
Your second example is putting a nested array in companies. Here's a simplified idea of what's going on:
data = [{value: 1}, {value: 2}, {value: 3}]
foo = []
data.each do |number|
foo << number[:value]
end
p foo
# => [1,2,3] # One array with 3 values
foo = []
foo << data.map { |item| item[:value] }
p foo
# => [[1,2,3]] # One array with one value (another array with 3 values)
Either stick with your first version, or just do this:
companies = current_user.cached_company.cached_companies.map(&:id)
Or, if you want to stick with your 2nd version, make sure to flatten the values before you use them:
companies.flatten!