Menu
  • HOME
  • TAGS

Why is `for i in a` not idiomatic Ruby? [closed]

Tag: ruby,for-loop,coding-style,iterator

Ruby has support for the for i in a syntax, but no one really uses it. One of the design principles of Ruby is it's readability, and I find

for i in a
  ...
end

much more readable (and easier to type) than

a.each do |i|
  ...
end

Why is it not preferred? Do others not also find it more readable? Is it for consistency reasons, e.g., relation with other functions like each_with_index and variable scoping?

Best How To :

For me, it's uniform syntax. When I am going to do something with array a, I just start typing a.. What am I going to do? Filter? a.select; determine the size? a.size. Iterate? a.each etc.

Iterating an array is nothing special and requires no special language construct. Also eachwithout an immediate block results in an Enumerator, which can be chained with other methods.

Then again, Ruby does have a fine for i in a loop. So if you are more comfortable with a for loop: by all means, use a for loop.

Same enum values for multiple columns

ruby-on-rails,ruby,enums

Maybe it makes extract the planet as another model? def Planet enum type: %w(earth mars jupiter) end class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet' end You can create a PlanetEdge by using accepts_nested_attributes_for: class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet'...

php for loop of an array

php,html,arrays,for-loop

Assuming you have properly named the input values, e.g.: <input name="topay[0]" type="checkbox"> <input name="loadnum[0]" value="5"> <input name="unit[0]" value="101"> <input name="driver[0]" value="joe"> <input name="topay[1]" type="checkbox"> <input name="loadnum[1]" value="6"> <input name="unit[1]" value="103"> <input name="driver[1]" value="mike"> Take note of the topay[0] and topay[1] notation that I'm using, as opposed to your form input...

For loop with flexible stop variable

ruby

Normally we'd use a loop do with a guard clause: x = 1 loop do break if x >= y x += 1 ... end Make sure y is larger than x or it'll never do anything. y can change if necessary and as long as it's greater than x...

rails - NameError (undefined local variable or method while using has_many :through

ruby-on-rails,ruby,ruby-on-rails-4

In your associations instead of fac_allocs you need to use a symbol because rails is looking a variable or method named fac_allocs instead of your associated model has_many :facs, through: :fac_allocs ...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

Rails - link_to path based on object's name + refactoring multiple custom actions

ruby-on-rails,ruby,refactoring

You can change your routes : resources :techs, :only => [:index, :show], shallow: true do resources :cars, only: [:new, :create] collection do get 'part/:part_name' => "techs#part", as: :part end end Then add the action : def part @techs = Tech.joins(:services).where(services: { name: params[:part_name]}) end and the view will be :...

Rails less url path change

ruby-on-rails,ruby,url,path,less

You should use the font_url, and put the font in app/assets/fonts @font-face { font-family: 'SomeFont'; src: font_url("db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } ...

Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku

Your migration file named should correspond to AddWeightToExercises. It should be accordingly xxxxxxxx_add_weight_to_exercises, where xxxxxxx corresponds to a particular timestamp.

Keep leading zeroes when converting string to integer

ruby

Short answer: no, you cant. 2.1.5 :001 > 0001 => 1 0001 doesn't make sense at all as Integer. In the Integer world, 0001 is exactly as 1. Moreover, the number of leading integer is generally irrelevant, unless you need to pad some integer for displaying, but in this case...

How could I padding spaces to a fix length

ruby

You should use ljust: arr = [477, 4770] strings = arr.map { |number| number.to_s.ljust(5) } # => ["477 ", "4770 "] Good luck!...

Why cant I refer to a random index in my 4D list, while I know it exists?

c#,list,for-loop,dimensions

Based on your code where you're filling your 4D list: List<string> Lijst1D = new List<string>(); Lijst2D.Add(Lijst1D); Here you're creating new List<string> and adding it to parent 2D list. But Lijst1D itself doesn't contains any elements (you haven't added anything to it), so Lijst4D[0] will throw that IndexOutOfRangeException as well as...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

It's not "through Hash", it's "array access" operator. To implement it, you need to define methods: def [](*keys) # Define here end def []=(*keys, value) # Define here end Of course, if you won't be using multiple keys to access an element, you're fine with using just key instead of...

On rendering from controller, current_page method does not seem to work

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller

You can use content_for and yields to create a default in your layout which views can override. # layouts/application.html.erb: <% if content_for?(:banner) %> <%= yield(:banner) %> <% else %> <div id="banner"> <h1>This is the default...</h1> </div> <% end %> /users/signup.html.erb: <%- content_for :banner, flush: true do -%> <!-- move along,...

Rails basic auth not working properly

ruby-on-rails,ruby,authentication

@user.keys.each do |key| username == key.api_id && password == key.api_key end This piece of code returns a value of .each, which is the collection it's called on (@user.keys in this case). As it is a truthy value, the check will pass always, regardless of what are the results of evaluating...

How to iterate through a table in its exact order?

loops,for-loop,lua,order

You may utilize integer part of the table to store keys in order: function add(t, k, v, ...) if k ~= nil then t[k] = v t[#t+1] = k return add(t, ...) end return t end t = add({ }, "A", "hi", "B", "my", "C", "name", "D", "is") for i,k...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many

Take a look at merit gem. Even if you want to develop your own badge system from scratch this gem contains plenty of nice solutions you can use. https://github.com/merit-gem/merit

Heroku RAM not increasing with upgraded dynos

ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku

That log excert is from a one off dyno, a la heroku run console - this is entirely seperate to your web dynos which you may be runnning 2x dyno's for. You need to specifiy --size=2x in your heroku run command to have the one off process use 2x dynos.

Python For Loop Using Math Operators

python,for-loop

Just as a loop is introduced by for, does not imply the same behaviour for different languages. Python's for loop iterates over objects. Something like the C-for loop does not exist. The C for loop (for ( <init> ; <cond> ; <update> ) <statement>, however, is actually identical to the...

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

ruby-on-rails,ruby,rack,multipart

Telling it short, this value limits the amount of simultaneously opened files for multipart requests. To understand better what is multipart, you can see this question. The reason for this limitation is an ability to better adjust your app for your server. If you have too many files opened at...

Using Ruby Pathname to access relative directory

ruby,path,pathname

You need add another level like p = Pathname.new('dir/.') now the directory name is "dir"...

Ruby gsub group parameters do not work when preceded by escaped slashes

ruby,regex

You are trying to write a python code using ruby syntax. This is not a best approach to GTD. Slashes are handled right-to-left, yielding not what you expected. As soon as one finds herself putting three or more backslashes inside the string, she should admit, she’s doing it wrong. At...

RSpec test for rake task

ruby-on-rails,ruby,rspec,rake-task

A couple things. First off, you should put created_at in the create method: user.items.create(description: "Old Item", created_at: 12.days.ago). Second, you need to call user.reload in order for the changes from your rake task to be available. So it should look like this: user.reload expect(user.items.count).to eq 1 etc...

edit first line of multiple files in place with a ruby one-liner

ruby

This code will work: ruby -pi -e 'sub(/^/,"New line goes at top\n") if $FILENAME != $F;$F = $FILENAME' file* ...

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4

You should pass actions to the included block and perform_search_on to the class_methods block. module Searchable extend ActiveSupport::Concern class_methods do def perform_search_on(klass, associations = {}) ............. end end included do def filter respond_to do |format| format.json { render 'api/search/filters.json' } end end end end When your Searchable module include a...

Ruby access words in string

ruby

What you are doing will access the fourth character of String s. Split the string to an array and then access the fourth element as follows. puts s.split[3] Note: Calling split without parameters separates the string by whitespace. Edit: Fixing indexes. The index starts from 0. That means s.split[3] will...

How to build a 'for' loop with input$i in R Shiny

r,loops,for-loop,shiny

Use [[ or [ if you want to subset by string names, not $. From Hadley's Advanced R, "x$y is equivalent to x[["y", exact = FALSE]]." ## Create input input <- `names<-`(lapply(landelist, function(x) sample(0:1, 1)), landelist) filterland <- c() for (landeselect in landelist) if (input[[landeselect]] == TRUE) # use `[[`...

Loop until i get correct user

ruby,redis

Change if to while: while ["user_4", "user_5"].include?(@randUser = @redis.spop("users")) do @redis.sadd("users", @randUser) end $user_username = @redis.hget(@randUser, "username") $user_password = @redis.hget(@randUser, "password") Please note, that you actually mixed up receiver and parameters on Array#include?...

Can't map a range of dates in Ruby/Rails

ruby-on-rails,ruby

You can try : dateLabels = <%= raw @mapped_dates.as_json %>; This will return ["Jan 1", "Jan 2", "Jan 3", ... ] For ActiveSupport::TimeWithZone problem, please do - In config/initializers/time_zone.rb class ActiveSupport::TimeWithZone def as_json(options = {}) if ActiveSupport::JSON::Encoding.use_standard_json_time_format xmlschema else %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) end end end ...

Map with accumulator on an array

ruby,inject

This operation is called scan or prefix_sum, but unfortunately, there is no implementation in the Ruby core library or standard libraries. However, your intuition is correct: you can implement it using Enumerable#inject. (Actually, Enumerable#inject is general, every iteration operation can be implemented using inject!) module Enumerable def scan(initial) inject([initial]) {|acc,...

is there an equivalent of the ruby any method in javascript?

javascript,arrays,ruby,iteration

You are looking for the Array.prototype.some method: var match = arr.some(function(w) { return w.indexOf('z') > -1; }); ...

In Ruby how to put multiple lines in one guard clause?

ruby-on-rails,ruby

Don't know what the surrounding code looks like so let's assume your code is the entire body of a method. Then a guard clause might look like this: def some_method return if params[:"available_#{district.id}"] != 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id) delivery_custom_price(district) end ...

Appending an element to a page in VoltRb

html,ruby,opalrb,voltrb

Ok, so the problem is that the code you have is being loaded as soon as the compiled .js file loads. You need to run the code once the DOM is ready. The easy way to do this in volt is to run it on a {action}_ready method: module Main...

Ruby- get a xml node value

ruby,xml

Try to use css instead of xpath, this will work for you, doc = Nokogiri::XML(response.body) values = doc.css('Name').select{|name| name.text}.join',' puts values => Ram,Sam ...

looping variable in swift

swift,for-loop,uiimage

You don't need to create a new variable for each image, try this: for var i = 1; i < 8; i++ { images.append(UIImage(named: "image\(i)")) } This loop will create an array with 8 images without create the variables image1 to image8. I hope that help you!...

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2

So, the complex part of your situation is that you have one thing (Surgery) that can be of many different types, and the different types have different fields. There are a number of different approaches to this problem, and I don't believe there's wide consensus on the 'best way'. The...

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter

If you express the relation properly, ActiveRecord will do it for you class Tweet belongs_to :original_tweet, class_name: Tweet has_many :retweets, class_name: Tweet, dependent: :destroy, inverse_of :original_tweet end Tweet.last.destroy # will now destroy dependents ...

Get the actual value of a boolean attribute

ruby,page-object-gem,rspec3,rspec-expectations

The Page-Object gem's attribute method does not do any formatting of the attribute value. It simply returns what is returned from Selenium-WebDriver (or Watir-Webdriver). In the case of boolean attributes, this means that true or false will be returned. From the Selenium-WebDriver#attribute documentation: The following are deemed to be “boolean”...

Call method to generate arguments in ruby works in 1.8.7 but not 1.9.3

ruby-on-rails,ruby,ruby-1.9.3

Change required (in github notation): - myFunction(submitArgs()) + myFunction(*submitArgs) The reason that [I assume] myFunction is declared taking two arguments: def myFunction a1, a2 Hence the array must be splatted before passing to it. I wonder how that worked in 1.8....

Ruby boolean logic: some amount of variables are true

ruby

[a, b, c].count(true) < 2 ........................

How to handle backslash “\” escape characters in q string and heredocument

ruby

str = <<'TEXT' hello %s \\\hline %s TEXT name = "Graig" msg = "Goodbye" puts str % [name, msg] The heredoc does not have escape chars when it's delimiter is in single quotes. It does have a form of interpolation. The code above has this output: hello Graig \\\hline Goodbye...

for-loop add columns using SQL in MS Access

sql,ms-access,table,for-loop,iteration

I have tested your code, I do not see any issues except for the fact, your For statement is a bit off and that you needed to set the db object. Try this code. Sub toto() Dim db As Database, i As Integer Set db = CurrentDb For i =...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations

Found this : Validating nested association in Rails (last chapter) class User belongs_to :organization, inverse_of: :users validates_presence_of :organization_id, :unless => 'usertype==1' end class Organization has_many :users accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true end The documentation is not quite clear about it but I think it's worth a try....

String#scan not capturing all occurences

ruby,regex

The reason is that after finding the first result, the regex engine continues its walk at the position after this first result. So the zero at the end of the first result can't be reuse for an other result. The way to get overlapping results is to put your pattern...

How to get return value from a forked / spawned process in Ruby?

ruby,process,output,fork,spawn

There are a whole bunch of ways to run commands from Ruby. The simplest for your case is to use backticks, which capture output: `sleep 10; date` # "Tue Jun 23 10:15:39 EDT 2015\n" If you want something more similar to Process.spawn, use the open3 stdlib: require 'open3' stdin, stdout,...

Split an array into slices, with groupings

arrays,ruby,enumerable

Yes, this bookkeeping with i is usually a sign there should be something better. I came up with: ar =[ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name:...

Allowing some enabled and disabled option on collection_select

ruby-on-rails,ruby

collection_select internally relies on options_from_collection_for_select helper. Rather than using the collection_select directly, you can use select and pass the result of a options_from_collection_for_select call. The reason you may want to call options_from_collection_for_select directly, is because this method also accepts an optional selected parameter that could be used to pass a...

regex to pull in number with decimal or comma

ruby,regex

\d+(?:[,.]\d+)? Try this.This should do it for you....

Get X days out of an Array

ruby,ruby-on-rails-4

I would do: def get_days(wkn, *desired_days) get_week = Model.week(2) get_days_of_week = get_week.select { |x| desired_days.include? x.strftime("%A") } end ...

Javascript: Forloop Difference between i++ and (i+1)

javascript,loops,for-loop

The i++ is using post increment, so the value of the expression i++ is what the value was in the variable i before the increment. This code: if(sortedLetters[i] !== sortedLetters[i++]) return true; does the same thing as: if(sortedLetters[i] !== sortedLetters[i]) return true; i = i + 1; As x !==...