kandi background
Explore Kits

sinatra | Classy web-development | Web Framework library

 by   sinatra Ruby Version: Current License: MIT

 by   sinatra Ruby Version: Current License: MIT

Download this library from

kandi X-RAY | sinatra Summary

sinatra is a Ruby library typically used in Server, Web Framework, Ruby On Rails, Framework applications. sinatra has no bugs, it has a Permissive License and it has medium support. However sinatra has 1 vulnerabilities. You can download it from GitHub, GitLab.
Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort:. The code you changed will not take effect until you restart the server. Please restart the server every time you change or use sinatra/reloader. It is recommended to also run gem install puma, which Sinatra will pick up if available.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • sinatra has a medium active ecosystem.
  • It has 11519 star(s) with 2049 fork(s). There are 381 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 61 open issues and 723 have been closed. On average issues are closed in 239 days. There are 16 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of sinatra is current.
sinatra Support
Best in #Web Framework
Average in #Web Framework
sinatra Support
Best in #Web Framework
Average in #Web Framework

quality kandi Quality

  • sinatra has 0 bugs and 0 code smells.
sinatra Quality
Best in #Web Framework
Average in #Web Framework
sinatra Quality
Best in #Web Framework
Average in #Web Framework

securitySecurity

  • sinatra has 1 vulnerability issues reported (0 critical, 0 high, 1 medium, 0 low).
  • sinatra code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
sinatra Security
Best in #Web Framework
Average in #Web Framework
sinatra Security
Best in #Web Framework
Average in #Web Framework

license License

  • sinatra is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
sinatra License
Best in #Web Framework
Average in #Web Framework
sinatra License
Best in #Web Framework
Average in #Web Framework

buildReuse

  • sinatra releases are not available. You will need to build from source code and install.
  • Installation instructions are not available. Examples and code snippets are available.
  • sinatra saves you 8366 person hours of effort in developing the same functionality from scratch.
  • It has 16898 lines of code, 877 functions and 164 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
sinatra Reuse
Best in #Web Framework
Average in #Web Framework
sinatra Reuse
Best in #Web Framework
Average in #Web Framework
Top functions reviewed by kandi - BETA

kandi has reviewed sinatra and discovered the below as its top functions. This is intended to give you an instant insight into sinatra implemented functionality, and help decide if they suit your requirements.

  • Renders custom data .
    • Handles the error handling .
      • Compile a template
        • Process a given path and values .
          • Sets HTTP header value .
            • Invoke the request .
              • Runs the routes defined on the class .
                • Sends an HTTP request with the given options .
                  • Initializes the middleware .
                    • Finalize the client .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      sinatra Key Features

                      Classy web-development dressed in a DSL (official / canonical repo)

                      sinatra Examples and Code Snippets

                      See all related Code Snippets

                      Sinatra

                      copy iconCopydownload iconDownload
                      # myapp.rb
                      require 'sinatra'
                      
                      get '/' do
                        'Hello world!'
                      end
                      

                      Routes

                      copy iconCopydownload iconDownload
                      get '/' do
                        .. show something ..
                      end
                      
                      post '/' do
                        .. create something ..
                      end
                      
                      put '/' do
                        .. replace something ..
                      end
                      
                      patch '/' do
                        .. modify something ..
                      end
                      
                      delete '/' do
                        .. annihilate something ..
                      end
                      
                      options '/' do
                        .. appease something ..
                      end
                      
                      link '/' do
                        .. affiliate something ..
                      end
                      
                      unlink '/' do
                        .. separate something ..
                      end
                      

                      Conditions

                      copy iconCopydownload iconDownload
                      get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
                        "You're using Songbird version #{params['agent'][0]}"
                      end
                      
                      get '/foo' do
                        # Matches non-songbird browsers
                      end
                      

                      Return Values

                      copy iconCopydownload iconDownload
                      class Stream
                        def each
                          100.times { |i| yield "#{i}\n" }
                        end
                      end
                      
                      get('/') { Stream.new }
                      

                      Custom Route Matchers

                      copy iconCopydownload iconDownload
                      class AllButPattern
                        Match = Struct.new(:captures)
                      
                        def initialize(except)
                          @except   = except
                          @captures = Match.new([])
                        end
                      
                        def match(str)
                          @captures unless @except === str
                        end
                      end
                      
                      def all_but(pattern)
                        AllButPattern.new(pattern)
                      end
                      
                      get all_but("/index") do
                        # ...
                      end
                      

                      Static Files

                      copy iconCopydownload iconDownload
                      set :public_folder, __dir__ + '/static'
                      

                      Views / Templates

                      copy iconCopydownload iconDownload
                      get '/' do
                        erb :index
                      end
                      

                      Literal Templates

                      copy iconCopydownload iconDownload
                      get '/' do
                        haml '%div.title Hello World'
                      end
                      

                      Available Template Languages

                      copy iconCopydownload iconDownload
                      require 'rdiscount' # or require 'bluecloth'
                      get('/') { markdown :index }
                      

                      Accessing Variables in Templates

                      copy iconCopydownload iconDownload
                      get '/:id' do
                        @foo = Foo.find(params['id'])
                        haml '%h1= @foo.name'
                      end
                      

                      Templates with

                      copy iconCopydownload iconDownload
                      erb :post, :layout => false do
                        erb :index
                      end
                      

                      Inline Templates

                      copy iconCopydownload iconDownload
                      require 'sinatra'
                      
                      get '/' do
                        haml :index
                      end
                      
                      __END__
                      
                      @@ layout
                      %html
                        = yield
                      
                      @@ index
                      %div.title Hello world.
                      

                      Named Templates

                      copy iconCopydownload iconDownload
                      template :layout do
                        "%html\n  =yield\n"
                      end
                      
                      template :index do
                        '%div.title Hello World!'
                      end
                      
                      get '/' do
                        haml :index
                      end
                      

                      Associating File Extensions

                      copy iconCopydownload iconDownload
                      Tilt.register :tt, Tilt[:textile]
                      

                      Adding Your Own Template Engine

                      copy iconCopydownload iconDownload
                      Tilt.register :myat, MyAwesomeTemplateEngine
                      
                      helpers do
                        def myat(*args) render(:myat, *args) end
                      end
                      
                      get '/' do
                        myat :index
                      end
                      

                      Using Custom Logic for Template Lookup

                      copy iconCopydownload iconDownload
                      configure do
                        set :views, [ './views/a', './views/b' ]
                      end
                      
                      def find_template(views, name, engine, &block)
                        Array(views).each do |v|
                          super(v, name, engine, &block)
                        end
                      end
                      

                      Filters

                      copy iconCopydownload iconDownload
                      before do
                        @note = 'Hi!'
                        request.path_info = '/foo/bar/baz'
                      end
                      
                      get '/foo/*' do
                        @note #=> 'Hi!'
                        params['splat'] #=> 'bar/baz'
                      end
                      

                      Helpers

                      copy iconCopydownload iconDownload
                      helpers do
                        def bar(name)
                          "#{name}bar"
                        end
                      end
                      
                      get '/:name' do
                        bar(params['name'])
                      end
                      

                      Using Sessions

                      copy iconCopydownload iconDownload
                      enable :sessions
                      
                      get '/' do
                        "value = " << session[:value].inspect
                      end
                      
                      get '/:value' do
                        session['value'] = params['value']
                      end
                      

                      Halting

                      copy iconCopydownload iconDownload
                      halt
                      

                      Passing

                      copy iconCopydownload iconDownload
                      get '/guess/:who' do
                        pass unless params['who'] == 'Frank'
                        'You got me!'
                      end
                      
                      get '/guess/*' do
                        'You missed!'
                      end
                      

                      Triggering Another Route

                      copy iconCopydownload iconDownload
                      get '/foo' do
                        status, headers, body = call env.merge("PATH_INFO" => '/bar')
                        [status, headers, body.map(&:upcase)]
                      end
                      
                      get '/bar' do
                        "bar"
                      end
                      

                      Setting Body, Status Code, and Headers

                      copy iconCopydownload iconDownload
                      get '/foo' do
                        body "bar"
                      end
                      
                      after do
                        puts body
                      end
                      

                      Streaming Responses

                      copy iconCopydownload iconDownload
                      get '/' do
                        stream do |out|
                          out << "It's gonna be legen -\n"
                          sleep 0.5
                          out << " (wait for it) \n"
                          sleep 1
                          out << "- dary!\n"
                        end
                      end
                      

                      Logging

                      copy iconCopydownload iconDownload
                      get '/' do
                        logger.info "loading data"
                        # ...
                      end
                      

                      Mime Types

                      copy iconCopydownload iconDownload
                      configure do
                        mime_type :foo, 'text/foo'
                      end
                      

                      Generating URLs

                      copy iconCopydownload iconDownload
                      %a{:href => url('/foo')} foo
                      

                      Browser Redirect

                      copy iconCopydownload iconDownload
                      get '/foo' do
                        redirect to('/bar')
                      end
                      

                      Cache Control

                      copy iconCopydownload iconDownload
                      get '/' do
                        cache_control :public
                        "cache it!"
                      end
                      

                      Sending Files

                      copy iconCopydownload iconDownload
                      get '/' do
                        send_file 'foo.png'
                      end
                      

                      Accessing the Request Object

                      copy iconCopydownload iconDownload
                      # app running on http://example.com/example
                      get '/foo' do
                        t = %w[text/css text/html application/javascript]
                        request.accept              # ['text/html', '*/*']
                        request.accept? 'text/xml'  # true
                        request.preferred_type(t)   # 'text/html'
                        request.body                # request body sent by the client (see below)
                        request.scheme              # "http"
                        request.script_name         # "/example"
                        request.path_info           # "/foo"
                        request.port                # 80
                        request.request_method      # "GET"
                        request.query_string        # ""
                        request.content_length      # length of request.body
                        request.media_type          # media type of request.body
                        request.host                # "example.com"
                        request.get?                # true (similar methods for other verbs)
                        request.form_data?          # false
                        request["some_param"]       # value of some_param parameter. [] is a shortcut to the params hash.
                        request.referrer            # the referrer of the client or '/'
                        request.user_agent          # user agent (used by :agent condition)
                        request.cookies             # hash of browser cookies
                        request.xhr?                # is this an ajax request?
                        request.url                 # "http://example.com/example/foo"
                        request.path                # "/example/foo"
                        request.ip                  # client IP address
                        request.secure?             # false (would be true over ssl)
                        request.forwarded?          # true (if running behind a reverse proxy)
                        request.env                 # raw env hash handed in by Rack
                      end
                      

                      Attachments

                      copy iconCopydownload iconDownload
                      get '/' do
                        attachment
                        "store it!"
                      end
                      

                      Dealing with Date and Time

                      copy iconCopydownload iconDownload
                      get '/' do
                        pass if Time.now > time_for('Dec 23, 2016')
                        "still time"
                      end
                      

                      Looking Up Template Files

                      copy iconCopydownload iconDownload
                      find_template settings.views, 'foo', Tilt[:haml] do |file|
                        puts "could be #{file}"
                      end
                      

                      Configuration

                      copy iconCopydownload iconDownload
                      configure do
                        # setting one option
                        set :option, 'value'
                      
                        # setting multiple options
                        set :a => 1, :b => 2
                      
                        # same as `set :option, true`
                        enable :option
                      
                        # same as `set :option, false`
                        disable :option
                      
                        # you can also have dynamic settings with blocks
                        set(:css_dir) { File.join(views, 'css') }
                      end
                      

                      Configuring attack protection

                      copy iconCopydownload iconDownload
                      disable :protection
                      

                      Environments

                      copy iconCopydownload iconDownload
                      APP_ENV=production ruby my_app.rb
                      

                      Not Found

                      copy iconCopydownload iconDownload
                      not_found do
                        'This is nowhere to be found.'
                      end
                      

                      Error

                      copy iconCopydownload iconDownload
                      set :show_exceptions, :after_handler
                      

                      Rack Middleware

                      copy iconCopydownload iconDownload
                      require 'sinatra'
                      require 'my_custom_middleware'
                      
                      use Rack::Lint
                      use MyCustomMiddleware
                      
                      get '/hello' do
                        'Hello World'
                      end
                      

                      Testing

                      copy iconCopydownload iconDownload
                      require 'my_sinatra_app'
                      require 'minitest/autorun'
                      require 'rack/test'
                      
                      class MyAppTest < Minitest::Test
                        include Rack::Test::Methods
                      
                        def app
                          Sinatra::Application
                        end
                      
                        def test_my_default
                          get '/'
                          assert_equal 'Hello World!', last_response.body
                        end
                      
                        def test_with_params
                          get '/meet', :name => 'Frank'
                          assert_equal 'Hello Frank!', last_response.body
                        end
                      
                        def test_with_user_agent
                          get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
                          assert_equal "You're using Songbird!", last_response.body
                        end
                      end
                      

                      Sinatra::Base - Middleware, Libraries, and Modular Apps

                      copy iconCopydownload iconDownload
                      require 'sinatra/base'
                      
                      class MyApp < Sinatra::Base
                        set :sessions, true
                        set :foo, 'bar'
                      
                        get '/' do
                          'Hello world!'
                        end
                      end
                      

                      Serving a Modular Application

                      copy iconCopydownload iconDownload
                      # my_app.rb
                      require 'sinatra/base'
                      
                      class MyApp < Sinatra::Base
                        # ... app code here ...
                      
                        # start the server if ruby file executed directly
                        run! if app_file == $0
                      end
                      

                      Using a Classic Style Application with a config.ru

                      copy iconCopydownload iconDownload
                      # app.rb
                      require 'sinatra'
                      
                      get '/' do
                        'Hello world!'
                      end
                      

                      Using Sinatra as Middleware

                      copy iconCopydownload iconDownload
                      require 'sinatra/base'
                      
                      class LoginScreen < Sinatra::Base
                        enable :sessions
                      
                        get('/login') { haml :login }
                      
                        post('/login') do
                          if params['name'] == 'admin' && params['password'] == 'admin'
                            session['user_name'] = params['name']
                          else
                            redirect '/login'
                          end
                        end
                      end
                      
                      class MyApp < Sinatra::Base
                        # middleware will run before filters
                        use LoginScreen
                      
                        before do
                          unless session['user_name']
                            halt "Access denied, please <a href='/login'>login</a>."
                          end
                        end
                      
                        get('/') { "Hello #{session['user_name']}." }
                      end
                      

                      Dynamic Application Creation

                      copy iconCopydownload iconDownload
                      require 'sinatra/base'
                      my_app = Sinatra.new { get('/') { "hi" } }
                      my_app.run!
                      

                      Application/Class Scope

                      copy iconCopydownload iconDownload
                      class MyApp < Sinatra::Base
                        # Hey, I'm in the application scope!
                        set :foo, 42
                        foo # => 42
                      
                        get '/foo' do
                          # Hey, I'm no longer in the application scope!
                        end
                      end
                      

                      Request/Instance Scope

                      copy iconCopydownload iconDownload
                      class MyApp < Sinatra::Base
                        # Hey, I'm in the application scope!
                        get '/define_route/:name' do
                          # Request scope for '/define_route/:name'
                          @value = 42
                      
                          settings.get("/#{params['name']}") do
                            # Request scope for "/#{params['name']}"
                            @value # => nil (not the same request)
                          end
                      
                          "Route defined!"
                        end
                      end
                      

                      Command Line

                      copy iconCopydownload iconDownload
                      ruby myapp.rb [-h] [-x] [-q] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER]
                      

                      Multi-threading

                      copy iconCopydownload iconDownload
                      # config.ru
                      
                      require 'sinatra/base'
                      
                      class App < Sinatra::Base
                        get '/' do
                          "Hello, World"
                        end
                      end
                      
                      run App
                      

                      The Bleeding Edge

                      copy iconCopydownload iconDownload
                      gem install sinatra --pre
                      

                      With Bundler

                      copy iconCopydownload iconDownload
                      gem install bundler
                      

                      iterate over columns to count words in a sentence and put it in a new column

                      copy iconCopydownload iconDownload
                      cupid %>% 
                        mutate(across(starts_with("essay"), \(x) stringr::str_count(x, " +") + 1,
                                      .names = "{.col}_num"))
                      # ...other column...
                      #  essay0_num essay1_num essay2_num essay3_num essay4_num essay5_num essay6_num essay7_num
                      # 1        237         45         16         28         62          5          4         16
                      # 2        130          7         18          1         50         53          1          1
                      # 3        246         90         65         46        355          6          1          6
                      # 4         11          7         13          7         29          1          4          1
                      # 5         40          6          7          8         44          1          1          1
                      # 6        160         12         60         15         70         59         20          4
                      #   essay8_num essay9_num
                      # 1         14         30
                      # 2         10          1
                      # 3         12         39
                      # 4          1          4
                      # 5          1          1
                      # 6         17          2
                      

                      Why does Pagy return nil in Sinatra?

                      copy iconCopydownload iconDownload
                      @pagy, @articles = pagy(@articles.order(position: :desc), items: 50)
                      erb :'folders/show_folder'
                      
                      erb :'folders/show_folder'
                      @pagy, @articles = pagy(@articles.order(position: :desc), items: 50)
                      
                      @pagy, @articles = pagy(@articles.order(position: :desc), items: 50)
                      erb :'folders/show_folder'
                      
                      erb :'folders/show_folder'
                      @pagy, @articles = pagy(@articles.order(position: :desc), items: 50)
                      

                      How to programmatically get Sinatra's active port?

                      copy iconCopydownload iconDownload
                      require 'sinatra'
                      require 'socket'
                      
                      socket = Socket.new(:INET, :STREAM, 0)
                      socket.bind(Addrinfo.tcp("127.0.0.1", 0))
                      
                      port = socket.local_address.ip_port
                      socket.close
                      
                      set :port, port
                      set :bind, "127.0.0.1"
                      
                      get "/" do
                          "Hello, World!"
                      end
                      

                      Thin server on Elastic Beanstalk Runy 2.6 on AMI Linux V2

                      copy iconCopydownload iconDownload
                      daemonize: false
                      

                      Fix Your Ruby version is 2.6.8, but your gemfile specified 2.5.5

                      copy iconCopydownload iconDownload
                      /usr/local/bin/bundle
                      
                      /Users/Mahmoud/.rbenv/shims/ruby
                      
                      export PATH="$HOME/.rbenv/shims:$PATH"
                      eval "$(rbenv init -)"
                      
                      /Users/Mahmoud/.rbenv/shims/bundle
                      
                      /usr/local/bin/bundle
                      
                      /Users/Mahmoud/.rbenv/shims/ruby
                      
                      export PATH="$HOME/.rbenv/shims:$PATH"
                      eval "$(rbenv init -)"
                      
                      /Users/Mahmoud/.rbenv/shims/bundle
                      
                      /usr/local/bin/bundle
                      
                      /Users/Mahmoud/.rbenv/shims/ruby
                      
                      export PATH="$HOME/.rbenv/shims:$PATH"
                      eval "$(rbenv init -)"
                      
                      /Users/Mahmoud/.rbenv/shims/bundle
                      
                      /usr/local/bin/bundle
                      
                      /Users/Mahmoud/.rbenv/shims/ruby
                      
                      export PATH="$HOME/.rbenv/shims:$PATH"
                      eval "$(rbenv init -)"
                      
                      /Users/Mahmoud/.rbenv/shims/bundle
                      

                      trying to fix a rack lint error and 500 on GET /cable

                      copy iconCopydownload iconDownload
                      class ::Rack::Lint
                        alias check_status_orig check_status
                        alias check_headers_orig check_headers
                        alias check_content_type_orig check_content_type
                        alias check_content_length_orig check_content_length
                        alias check_hijack_orig check_hijack
                        alias _call_orig _call
                      
                        def _call(env)
                          @web_socket = env['REQUEST_PATH'] == '/cable'
                          _call_orig(env)
                        end
                      
                        def check_status(status)
                          return if @web_socket
                          check_status_orig(status)
                        end
                      
                        def check_headers(headers)
                          return if @web_socket
                          check_headers_orig(headers)
                        end
                      
                        def check_content_type(status, headers)
                          return if @web_socket
                          check_content_type_orig(status, headers)
                        end
                      
                        def check_content_length(status, headers)
                          return if @web_socket
                          check_content_type_orig(status, headers)
                        end
                      
                        def check_hijack(env)
                          # Don't know why, but HijackWrapper break WebSocket!
                          return if @web_socket
                          check_hijack_orig(env)
                        end
                      end
                      

                      Sidekiq jobs not queueing on rails app deployed to heroku

                      copy iconCopydownload iconDownload
                      heroku ps:scale low_worker=1
                      

                      How do I configure nginx correctly to work with my Sinatra app running on thin?

                      copy iconCopydownload iconDownload
                      location / {
                        proxy_pass http://localhost:4567;
                      }
                              
                      

                      Setting environment variables for a Sinatra app on Heroku

                      copy iconCopydownload iconDownload
                      MY_APP_SECRET=123qwerty shotgun config.ru
                      

                      Using a Docker image to run bundle install ignores bundle config setting

                      copy iconCopydownload iconDownload
                      $ docker run --rm -it -v $PWD:/src --workdir /src --entrypoint /bin/sh ruby:alpine
                      
                      /src # ls -l
                      total 0
                      
                      /src # echo $BUNDLE_APP_CONFIG
                      /usr/local/bundle
                      
                      /src # export BUNDLE_APP_CONFIG=$PWD/.bundler
                      
                      $ bundle config set --local path 'vendor/bundle'
                      /src # ls -la
                      total 4
                      drwxr-xr-x    3 root     root            96 Dec 16 21:10 .
                      drwxr-xr-x    1 root     root          4096 Dec 16 21:10 ..
                      drwxr-xr-x    3 root     root            96 Dec 16 21:10 .bundler
                      
                      /src # bundle config
                      Settings are listed in order of priority. The top value will be used.
                      app_config
                      Set via BUNDLE_APP_CONFIG: "/src/.bundler"
                      
                      path
                      Set for your local app (/src/.bundler/config): "vendor/bundle"
                      
                      silence_root_warning
                      Set via BUNDLE_SILENCE_ROOT_WARNING: true
                      
                      /src # bundle init
                      Writing new Gemfile to /src/Gemfile
                      
                      /src # echo 'gem "sinatra"' >> Gemfile
                      
                      /src # bundle install --quiet
                      
                      /src # ls -l
                      total 8
                      -rw-r--r--    1 root     root           161 Dec 16 21:12 Gemfile
                      -rw-r--r--    1 root     root           398 Dec 16 21:13 Gemfile.lock
                      drwxr-xr-x    3 root     root            96 Dec 16 21:18 vendor
                      
                      /src # du -sh vendor/bundle/
                      3.1M    vendor/bundle/
                      
                      /src # bundle exec rackup --version
                      Rack 1.3 (Release: 2.2.3)
                      
                      /src # exit
                      
                      $ ls -ax1
                      .
                      ..
                      .bundler
                      Gemfile
                      Gemfile.lock
                      vendor
                      

                      See all related Code Snippets

                      Community Discussions

                      Trending Discussions on sinatra
                      • iterate over columns to count words in a sentence and put it in a new column
                      • Why does Pagy return nil in Sinatra?
                      • How to programmatically get Sinatra's active port?
                      • Thin server on Elastic Beanstalk Runy 2.6 on AMI Linux V2
                      • Fix Your Ruby version is 2.6.8, but your gemfile specified 2.5.5
                      • trying to fix a rack lint error and 500 on GET /cable
                      • Sidekiq jobs not queueing on rails app deployed to heroku
                      • How do I configure nginx correctly to work with my Sinatra app running on thin?
                      • Sinatra + Thin + Nginx connect() failed (111: Connection refused) while connecting to upstream
                      • Systemd service for Sinatra + Thin keeps restarting
                      Trending Discussions on sinatra

                      QUESTION

                      iterate over columns to count words in a sentence and put it in a new column

                      Asked 2022-Apr-08 at 04:54

                      I have some columns titles essay 0-9, I want to iterate over them count the words and then make a new column with the number of words. so essay0 will get a column essay0_num with 5 if that is how many words it has in it.

                      so far i got cupid <- cupid %>% mutate(essay9_num = sapply(strsplit(essay9, " "), length)) to count the words and add a column but i don't want to do it one by one for all 10.

                      i tried a for loop:

                      for (i in 0:31) {
                         cupid <- cupid %>% mutate(xxx_num = sapply(strsplit(xxx, " "), length))
                      }
                      

                      but i am not sure how iterate the columns in a for loop in R. I thought maybe i can pull out the columns i need and put them into a new df and use sapply somehow that way? but i still run into the problem of iterating over the columns.

                      dput:

                      dput(head(cupid))
                      structure(list(age = c(22L, 35L, 38L, 23L, 29L, 29L), status = c("single", 
                      "single", "available", "single", "single", "single"), sex = c("m",
                      "m", "m", "m", "m", "m"), orientation = c("straight", "straight",
                      "straight", "straight", "straight", "straight"), body_type = c("a little extra",
                      "average", "thin", "thin", "athletic", "average"), diet = c("strictly anything",
                      "mostly other", "anything", "vegetarian", "", "mostly anything"
                      ), drinks = c("socially", "often", "socially", "socially", "socially", 
                      "socially"), drugs = c("never", "sometimes", "", "", "never",
                      ""), education = c("working on college/university", "working on space camp",
                      "graduated from masters program", "working on college/university",
                      "graduated from college/university", "graduated from college/university"
                      ), ethnicity = c("asian, white", "white", "", "white", "asian, black, other",
                      "white"), height = c(75, 70, 68, 71, 66, 67), income = c(-1L, 
                      80000L, -1L, 20000L, -1L, -1L), job = c("transportation", "hospitality / travel",
                      "", "student", "artistic / musical / writer", "computer / hardware / software"
                      ), last_online = c("2012-06-28-20-30", "2012-06-29-21-41", "2012-06-27-09-10",
                      "2012-06-28-14-22", "2012-06-27-21-26", "2012-06-29-19-18"),
                          location = c("south san francisco, california", "oakland, california",
                          "san francisco, california", "berkeley, california", "san francisco, california", 
                          "san francisco, california"), offspring = c("doesn't have kids, but might want them",
                          "doesn't have kids, but might want them", "", "doesn't want kids",
                          "", "doesn't have kids, but might want them"), pets = c("likes dogs and likes cats",
                          "likes dogs and likes cats", "has cats", "likes cats", "likes dogs and likes cats",
                          "likes cats"), religion = c("agnosticism and very serious about it",
                          "agnosticism but not too serious about it", "", "", "", "atheism"
                          ), sign = c("gemini", "cancer", "pisces but it doesn&rsquo;t matter",
                          "pisces", "aquarius", "taurus"), smokes = c("sometimes",
                          "no", "no", "no", "no", "no"), speaks = c("english", "english (fluently), spanish (poorly), french (poorly)",
                          "english, french, c++", "english, german (poorly)", "english",
                          "english (fluently), chinese (okay)"), essay0 = c("about me:  i would love to think that i was some some kind of intellectual: either the dumbest smart guy, or the smartest dumb guy. can't say i can tell the difference. i love to talk about ideas and concepts. i forge odd metaphors instead of reciting cliches. like the simularities between a friend of mine's house and an underwater salt mine. my favorite word is salt by the way (weird choice i know). to me most things in life are better as metaphors. i seek to 
                      make myself a little better everyday, in some productively lazy way. got tired of tying my shoes. considered hiring a five year old, but would probably have to tie both of our shoes... decided to only wear leather shoes dress shoes.  about you:  you love to have really serious, really deep conversations about really silly stuff. you have to be willing to snap me out of a light hearted rant with a kiss. you don't have to be funny, but you have to be able to make me laugh. you should be able to bend spoons with your 
                      mind, and telepathically make me smile while i am still at work. you should love life, and be cool with just letting the wind blow. extra points for reading all this and guessing my favorite video game (no hints given yet). and lastly you have a good attention span.",
                          "i am a chef: this is what that means. 1. i am a workaholic. 2. i love to cook regardless of whether i am at work. 3. i love to drink and eat foods that are probably really bad for me. 4. i love being around people that resemble line 1-3. i love the outdoors and i am an avid skier. if its snowing i will be in tahoe at the very least. i am a very confident and friendly. i'm not interested in acting or being a typical guy. i have no time or patience for rediculous acts of territorial pissing. overall i am a very 
                      likable easygoing individual. i am very adventurous and always looking forward to doing new things and hopefully sharing it with the right person.",
                          "i'm not ashamed of much, but writing public text on an online dating site makes me pleasantly uncomfortable. i'll try to be as earnest as possible in the noble endeavor of standing naked before the world.  i've lived in san francisco for 15 years, and both love it and find myself frustrated with its deficits. lots of great friends and acquaintances (which increases my apprehension to put anything on this site), but i'm feeling like meeting some new people that aren't just friends of friends. it's okay if you are a friend of a friend too. chances are, if you make it through the complex filtering process of multiple choice questions, lifestyle statistics, photo scanning, and these indulgent blurbs of text without moving quickly on to another search result, you are probably already a cultural peer and at most 2 people removed. at first, i thought i should say as little as possible here to avoid 
                      you, but that seems silly.  as far as culture goes, i'm definitely more on the weird side of the spectrum, but i don't exactly wear it on my sleeve. once you get me talking, it will probably become increasingly apparent that while i'd like to think of myself as just like everybody else (and by some definition i certainly am), most people don't see me that way. that's fine with me. most of the people i find myself gravitating towards are pretty weird themselves. you probably are too.",
                          "i work in a library and go to school. . .", "hey how's it going? currently vague on the profile i know, more to come soon. looking to meet new folks outside of my circle of friends. i'm pretty responsive on the reply tip, feel free to drop a line. cheers.",
                          "i'm an australian living in san francisco, but don't hold that against me. i spend most of my days trying to build cool stuff for my company. i speak mandarin and have been known to bust out chinese songs at karaoke. i'm pretty cheeky. someone asked me if that meant something about my arse, which i find really funny.  i'm a little oddball. i have a wild imagination; i like to think 
                      of the most improbable reasons people are doing things just for fun. i love to laugh and look for reasons to do so. occasionally this gets me in trouble because people think i'm laughing at them. sometimes i am, but more often i'm only laughing at myself.  i'm an entrepreneur (like everyone else in sf, it seems) and i love what i do. i enjoy parties and downtime in equal measure. intelligence really turns me on and i love people who can teach me new things."
                          ), essay1 = c("currently working as an international agent for a freight forwarding company. import, export, domestic you know the works. online classes and trying to better myself in my free time. perhaps a hours worth of a good book or a video game on a 
                      lazy sunday.",
                          "dedicating everyday to being an unbelievable badass.", "i make nerdy software for musicians, artists, and experimenters to indulge in their own weirdness, but i like to spend time away from the computer when working on my artwork (which is typically more 
                      concerned with group dynamics and communication, than with visual form, objects, or technology). i also record and deejay dance, noise, pop, and experimental music (most of which electronic or at least studio based). besides these relatively ego driven activities, i've been enjoying things like meditation and tai chi to try and gently flirt with ego death.",
                          "reading things written by old dead people", "work work work work + play",
                          "building awesome stuff. figuring out what's important. having adventures. looking for treasure."
                          ), essay2 = c("making people laugh. ranting about a good salting. finding simplicity in complexity, and complexity in simplicity.",
                          "being silly. having ridiculous amonts of fun wherever. being a smart ass. ohh and i can cook. ;)",
                          "improvising in different contexts. alternating between being present and decidedly outside of a moment, or trying to hold both at once. rambling intellectual conversations that hold said conversations in contempt while seeking to find something that transcends them. being critical while remaining generous. listening to and using body language--often performed in caricature or large 
                      gestures, if not outright interpretive dance. dry, dark, and raunchy humor.", 
                          "playing synthesizers and organizing books according to the library of congress classification system",
                          "creating imagery to look at: http://bagsbrown.blogspot.com/ http://stayruly.blogspot.com/",
                          "imagining random shit. laughing at aforementioned random shit. being goofy. articulating what i think and feel. convincing people i'm right. admitting when i'm wrong.  i'm also pretty good at helping people think through problems; my friends say i give good advice. and when i don't have a clue how to help, i will say: i give pretty good hug."
                          ), essay3 = c("the way i look. i am a six foot half asian, half caucasian mutt. it makes it tough not to notice me, and for me to blend in.",
                          "", "my large jaw and large glasses are the physical things people comment on the most. when sufficiently stimulated, i have an unmistakable cackle of a laugh. after that, it goes in more directions than i care to describe right now. maybe i'll come back to this.",
                          "socially awkward but i do my best", "i smile a lot and my inquisitive nature", 
                          "i have a big smile. i also get asked if i'm wearing blue-coloured contacts (no)."
                          ), essay4 = c("books: absurdistan, the republic, of mice and men (only book that made me want to cry), catcher in the rye, the prince.  movies: gladiator, operation valkyrie, the producers, down periscope.  shows: the borgia, arrested development, game of 
                      thrones, monty python  music: aesop rock, hail mary mallon, george thorogood and the delaware destroyers, felt  food: i'm down for anything.",
                          "i am die hard christopher moore fan. i don't really watch a lot of tv unless there is humor involved. i am kind of stuck on 90's alternative music. i am pretty much a fan of everything though... i do need to draw a line at most types of electronica.",    
                          "okay this is where the cultural matrix gets so specific, it's like being in the crosshairs.  for what it's worth, i find myself reading more non-fiction than fiction. it's usually some kind of philosophy, art, or science text by silly authors such as ranciere, de certeau, bataille, baudrillard, butler, stein, arendt, nietzche, zizek, etc. i'll often throw in some weird new age or pop-psychology book in the mix as well. as for fiction, i enjoy what little i've read of eco, perec, wallace, bolao, dick, vonnegut, atwood, delilo, etc. when i was young, i was a rabid asimov reader.  directors i find myself drawn to are makavejev, kuchar, jodorowsky, herzog, hara, klein, waters, verhoeven, ackerman, hitchcock, lang, gorin, goddard, miike, ohbayashi, tarkovsky, sokurov, warhol, etc. but i also like a good amount of \"trashy\" stuff. too much to name.  i definitely enjoy the character development that happens in long form episodic television over the course of 10-100 episodes, which a 1-2hr movie usually can't compete with. some of my recent tv favorites are: breaking bad, the wire, dexter, true blood, the prisoner, lost, fringe.  a smattered sampling of 
                      the vast field of music i like and deejay: art ensemble, sun ra, evan parker, lil wayne, dj funk, mr. fingers, maurizio, rob hood, dan bell, james blake, nonesuch recordings, omar souleyman, ethiopiques, fela kuti, john cage, meredith monk, robert ashley, terry riley, yoko ono, merzbow, tom tom club, jit, juke, bounce, hyphy, snap, crunk, b'more, kuduro, pop, noise, jazz, techno, house, 
                      acid, new/no wave, (post)punk, etc.  a few of the famous art/dance/theater folk that might locate my sensibility: andy warhol, bruce nauman, yayoi kusama, louise bourgeois, tino sehgal, george kuchar, michel duchamp, marina abramovic, gelatin, carolee schneeman, gustav metzger, mike kelly, mike smith, andrea fraser, gordon matta-clark, jerzy grotowski, samuel beckett, antonin artaud, tadeusz kantor, anna halperin, merce cunningham, etc. i'm clearly leaving out a younger generation of contemporary artists, many of whom are friends.  local food regulars: sushi zone, chow, ppq, pagolac, lers ros, burma superstar, minako, shalimar, delfina pizza, rosamunde, arinells, suppenkuche, cha-ya, blue plate, golden era, etc.",
                          "bataille, celine, beckett. . . lynch, jarmusch, r.w. fassbender. . . twin peaks & fishing w/ john joy division, throbbing gristle, cabaret voltaire. . . vegetarian pho and coffee",
                          "music: bands, rappers, musicians at the moment: thee oh sees. forever: wu-tang books: artbooks for days audiobooks: my collection, thick (thanks audible) shows: live ones food: with stellar friends whenever movies > tv podcast: radiolab, this american life, the moth, joe rogan, the champs",
                          "books: to kill a mockingbird, lord of the rings, 1984, the farseer trilogy.  music: the beatles, frank sinatra, john mayer, jason mraz, deadmau5, andrew bayer, everything on anjunadeep records, bach, satie.  tv shows: how i met your mother, scrubs, the west wing, breaking bad.  movies: star wars, the godfather pt ii, 500 days of summer, napoleon dynamite, american beauty, lotr  food: thai, vietnamese, shanghai dumplings, pizza!"
                          ), essay5 = c("food. water. cell phone. shelter.", "delicious porkness in all of its glories. my big ass doughboy's sinking into 15 new inches. my overly resilient liver. a good sharp knife. my ps3... it plays blurays too. ;) my over the top energy and my 
                      outlook on life... just give me a bag of lemons and see what happens. ;)",
                          "movement conversation creation contemplation touch humor",
                          "", "", "like everyone else, i love my friends and family, and need hugs, human contact, water and sunshine. let's take that as given.  1. something to build 2. something to sing 3. something to play on (my guitar would be first choice) 4. something to write/draw on 5. a big goal worth dreaming about 6. something to laugh at"
                          ), essay6 = c("duality and humorous things", "", "", "cats and german philosophy",
                          "", "what my contribution to the world is going to be and/or should be. and what's for breakfast. i love breakfast."
                          ), essay7 = c("trying to find someone to hang out with. i am down for anything except a club.", 
                          "", "viewing. listening. dancing. talking. drinking. performing.",
                          "", "", "out with my friends!"), essay8 = c("i am new to california and looking for someone to wisper my secrets to.",        
                          "i am very open and will share just about anything.", "when i was five years old, i was known as \"the boogerman\".",
                          "", "", "i cried on my first day at school because a bird shat on my head. true story."
                          ), essay9 = c("you want to be swept off your feet! you are tired of the norm. you want to catch a coffee or a bite. or if you 
                      want to talk philosophy.",
                          "", "you are bright, open, intense, silly, ironic, critical, caring, generous, looking for an exploration, rather than finding \"a match\" of some predetermined qualities.  i'm currently in a fabulous and open relationship, so you should be comfortable with that.",
                          "you feel so inclined.", "", "you're awesome.")), row.names = c(NA,
                      6L), class = "data.frame")
                      

                      ANSWER

                      Answered 2022-Apr-08 at 04:54

                      Use across() to apply the same function to multiple columns:

                      cupid %>% 
                        mutate(across(starts_with("essay"), \(x) stringr::str_count(x, " +") + 1,
                                      .names = "{.col}_num"))
                      # ...other column...
                      #  essay0_num essay1_num essay2_num essay3_num essay4_num essay5_num essay6_num essay7_num
                      # 1        237         45         16         28         62          5          4         16
                      # 2        130          7         18          1         50         53          1          1
                      # 3        246         90         65         46        355          6          1          6
                      # 4         11          7         13          7         29          1          4          1
                      # 5         40          6          7          8         44          1          1          1
                      # 6        160         12         60         15         70         59         20          4
                      #   essay8_num essay9_num
                      # 1         14         30
                      # 2         10          1
                      # 3         12         39
                      # 4          1          4
                      # 5          1          1
                      # 6         17          2
                      

                      I simplified your word counting logic - splitting on spaces and looking at the length is the same as counting the spaces and adding 1. Using " +" as a regex pattern means consecutive spaces will be lumped together.

                      Source https://stackoverflow.com/questions/71790948

                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                      Vulnerabilities

                      No vulnerabilities reported

                      Install sinatra

                      You can download it from GitHub, GitLab.
                      On a UNIX-like operating system, using your system’s package manager is easiest. However, the packaged Ruby version may not be the newest one. There is also an installer for Windows. Managers help you to switch between multiple Ruby versions on your system. Installers can be used to install a specific or multiple Ruby versions. Please refer ruby-lang.org for more information.

                      Support

                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

                      DOWNLOAD this Library from

                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      Share this Page

                      share link
                      Consider Popular Web Framework Libraries
                      Try Top Libraries by sinatra
                      Compare Web Framework Libraries with Highest Support
                      Compare Web Framework Libraries with Highest Quality
                      Compare Web Framework Libraries with Highest Security
                      Compare Web Framework Libraries with Permissive License
                      Compare Web Framework Libraries with Highest Reuse
                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.